Skip to content

Implementation of the Command Queue (Event Queue) pattern is added. #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Assets/Patterns/14. Command Queue (Event Queue).meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 57 additions & 0 deletions Assets/Patterns/14. Command Queue (Event Queue)/CommandQueue.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System.Collections.Generic;

namespace CommandQueuePattern
{
public class CommandQueue
{
// queue of commands
private readonly Queue<ICommand> _queue;

// it's true when a command is running
private bool _isPending;

public CommandQueue()
{
// create a queue
_queue = new Queue<ICommand>();

// no command is running
_isPending = false;
}

public void Enqueue(ICommand cmd)
{
// add a command
_queue.Enqueue(cmd);

// if no command is running, start to execute commands
if (!_isPending)
DoNext();
}

public void DoNext()
{
// if queue is empty, do nothing.
if (_queue.Count == 0)
return;

// get a command
var cmd = _queue.Dequeue();
// setting _isPending to true means this command is running
_isPending = true;
// listen to the OnFinished event
cmd.OnFinished += OnCmdFinished;
// execute command
cmd.Execute();
}

private void OnCmdFinished()
{
// current command is finished
_isPending = false;

// run the next command
DoNext();
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading