Skip to content

Commit f8ba96d

Browse files
authored
Merge pull request Habrador#6 from masoudarvishian/implement_command_queue
Implementation of the Command Queue (Event Queue) pattern is added.
2 parents aab66ed + fc8e84b commit f8ba96d

18 files changed

+2113
-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,57 @@
1+
using System.Collections.Generic;
2+
3+
namespace CommandQueuePattern
4+
{
5+
public class CommandQueue
6+
{
7+
// queue of commands
8+
private readonly Queue<ICommand> _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<ICommand>();
17+
18+
// no command is running
19+
_isPending = false;
20+
}
21+
22+
public void Enqueue(ICommand 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)