Skip to content

Commit 8428ebc

Browse files
Implementation of the Command Queue (Event Queue) pattern is added.
1 parent 3301586 commit 8428ebc

18 files changed

+2122
-0
lines changed

Assets/Patterns/14. Command Queue (Event Queue).meta

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using System;
2+
3+
namespace CommandQueuePattern
4+
{
5+
public abstract class CommandBase
6+
{
7+
public Action OnFinished { get; set; }
8+
9+
public abstract void Execute();
10+
11+
public abstract bool IsFinished { get; protected set; }
12+
13+
protected void CallOnFinished()
14+
{
15+
OnFinished?.Invoke();
16+
}
17+
}
18+
}

Assets/Patterns/14. Command Queue (Event Queue)/CommandBase.cs.meta

+11
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System.Collections.Generic;
2+
3+
namespace CommandQueuePattern
4+
{
5+
public class CommandQueue
6+
{
7+
// queue of commands
8+
private readonly Queue<CommandBase> _queue;
9+
10+
// it's true when a command is running
11+
private bool _isPending;
12+
13+
public CommandQueue()
14+
{
15+
// create a queue
16+
_queue = new Queue<CommandBase>();
17+
18+
// no command is running
19+
_isPending = false;
20+
}
21+
22+
public void Enqueue(CommandBase cmd)
23+
{
24+
// add a command
25+
_queue.Enqueue(cmd);
26+
27+
// if no command is running, start to execute commands
28+
if (!_isPending)
29+
DoNext();
30+
}
31+
32+
public void DoNext()
33+
{
34+
// if queue is empty, do nothing.
35+
if (_queue.Count == 0)
36+
return;
37+
38+
// get a command
39+
var cmd = _queue.Dequeue();
40+
// setting _isPending to true means this command is running
41+
_isPending = true;
42+
// listen to the OnFinished event
43+
cmd.OnFinished += OnCmdFinished;
44+
// execute command
45+
cmd.Execute();
46+
}
47+
48+
private void OnCmdFinished()
49+
{
50+
// current command is finished
51+
_isPending = false;
52+
53+
// run the next command
54+
DoNext();
55+
}
56+
}
57+
}

Assets/Patterns/14. Command Queue (Event Queue)/CommandQueue.cs.meta

+11
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)