Command design pattern


Jump to: navigation, search

Command Pattern

Image:Example.jpg


*This picture was taken from the internet.

The Command pattern is very simple to explain as you can see in the code below:

First of all, we need a bunch of classes as you can see:

This is just to use a Command pattern

class Invoker
{
    private Command command;
    public void SetCommand(Command command)
    {
      this.command = command;
    }
    public void ExecuteCommand()
    {
      command.Execute();
    }    
}

This is the method implementation: the business rule or logic. Sometimes you can use the methods in the concrete Command class to implement the real logic.

class Receiver
{
    public void Action()
    {
      Console.WriteLine("Called ...");
    }
}

This is just a contract.

abstract class Command
{
    protected Receiver receiver;
    public Command(Receiver receiver)
    {
      this.receiver = receiver;
    }
    public abstract void Execute();
}

Here the magical thing happens.

class ConcreteCommand : Command
{
    public ConcreteCommand(Receiver receiver) : base(receiver) 
    {  
    }
    public override void Execute()
    {
      receiver.Action();
    }
}

Lets see how to use it.

class MainApp
{
    static void Main()
    {
      Receiver receiver = new Receiver();
      // Remember that you don´t really need an receiver if you don´t want it.
      Command command = new ConcreteCommand(receiver);
      Invoker invoker = new Invoker();
      invoker.SetCommand(command);
      invoker.ExecuteCommand();
    }
}





Personal tools