Definition
GoF --> Encapsulate a command request as an object.
The Command pattern creates distance between the client that requests an operation and the object that can perform it.
Design
The Client has a certain way of saying what is required, usually in high-level and domain-specific terms. It thinks in terms of commands such as On, or Off. The Receivers and there may be several—know how to carry out these requests.
Best example is, we have Switches for TV and Light, Target/receiver. We need to Operator, Invoker, to on or off them. Operator only knows how to execute specific commands. The command object encapsulates the requested operation on the object from the operator. Operator is only execute the command given with the command.
UML Diagram
Code
Example I
/// <summary>
/// Operations
for the Target.
/// </summary>
public interface
IOperations
{
Boolean
IsOn { get; set;
}
void
On();
void
Off();
}
/// <summary>
/// The
interface that provides all commands
/// </summary>
public interface
ICommand
{
void
Execute();
}
/// <summary>
/// Invoker
/// </summary>
public class
Operator
{
public ICommand Command { get;
set; }
public void Execute()
{
Command.Execute();
}
}
/// <summary>
/// Receiver
or target
/// </summary>
public class
Light: IOperations
{
public Boolean IsOn { get;
set; }
public void On()
{
Console.WriteLine("Light is On.....");
IsOn = true;
}
public void Off()
{
Console.WriteLine("Light is Off.....");
IsOn = false;
}
}
public class
TV : IOperations
{
public Boolean IsOn { get;
set; }
public void On()
{
Console.WriteLine("TV is On.....");
IsOn = true;
}
public void Off()
{
Console.WriteLine("TV is Off.....");
IsOn = true;
}
}
/// <summary>
/// Command for turning On/Off
/// </summary>
public class
TurnOnOff: ICommand
{
private
readonly IOperations
_receiver;
public
TurnOnOff(IOperations receiver)

Join the conversation! Your thoughts help the community grow.