The pattern encapsulates the request as an object of its own. Usually, when one object makes a request for a second object to do an action, the first object will call a method of the second object and the second object would complete the task.
Common way:

Visualization of the Command design pattern:

In this way, the Sender doesn’t need to know about the receiver and the methods to call.
The Command pattern has another object that invokes the command object to complete whatever task it is supposed to do, called the invoker.
Command manager – keeps track of the commands. manipulates them and invokes them.
Invoker is like a secretary in company, keeps tracks of the tasks (memos) and executed at the right time.
One of the common purposes of using the Command pattern is to store and schedule different requests.
For example you can use the pattern to have an alarm ring in calendar software. When an event is created in the calendar, a command object could be created to ring the alarm. This command can be put onto a queue, so the command can be completed later when the event is actually scheduled to occur.
Another common purpose is to be undone or redone.

using System;
namespace DoFactory.GangOfFour.Command.Structural
{
class MainApp
{
static void Main()
{
// Create receiver, command, and invoker
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
// Set and execute command
invoker.SetCommand(command);
invoker.ExecuteCommand();
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The 'Command' abstract class
/// </summary>
abstract class Command
{
protected Receiver receiver;
// Constructor
public Command(Receiver receiver)
{
this.receiver = receiver;
}
public abstract void Execute();
}
class ConcreteCommand : Command
{
// Constructor
public ConcreteCommand(Receiver receiver) :
base(receiver)
{
}
public override void Execute()
{
receiver.Action();
}
}
class Receiver
{
public void Action()
{
Console.WriteLine("Called Receiver.Action()");
}
}
class Invoker
{
private Command _command;
public void SetCommand(Command command)
{
this._command = command;
}
public void ExecuteCommand()
{
_command.Execute();
}
}
}
One thought on “Command Pattern”