Introduction
Command design pattern encapsulates request as an object which has all the information needed to perform an action or invoke a method or trigger an event at later time. It supports undoable action.
It is a behavior design pattern.
It deals with below problems
1. Decouples the request receiver and request invoker.
2. Code is extensible as new Receiver and command be added in future.
UML Diagram
Example Basic structure program
using System;
public class Program{
public static void Main()}
{var receiver = new Receiver();var command = new ConcreteCommand(receiver);var invoker = new Invoker(command);invoker.DoAction();}
public class Receiver
{
public void DoOperation()}
{
Console.WriteLine("Receiver is doing the operation");
}
public interface ICommand
{
void Execute();
}
public class ConcreteCommand:ICommand
{
private Receiver _receiver;
public ConcreteCommand(Receiver receiver)
{
_receiver = receiver;
}
public void Execute(){_receiver.DoOperation();}
public class Invoker
{
private ICommand _command;
public Invoker(ICommand command)
{
_command = command;
}
{
_command.Execute();
}
}
In the above code, we can see Command and Invoker have been created separately. This means
Real World Example