Command Pattern - TechNet Articles - United States (English) - TechNet Wiki

A command pattern is a design pattern that enables all the information for a request to be contained within a single object. The command can then be invoked as required, ofte as a part of a batch of queued commands with rollback capabilities. 

There are three key terms which needed to be explained. 

1. Client : It creates the Command object.
2. Invoker : The invoker decides when the method needs information encapsulated within the command object. 
3. Receiver : It is the instance of the class which contains the method to be invoked. 

Implementation

public interface ICommand

Command Pattern

A command pattern is a design pattern that enables all the information for a requestckground-color:#f8f8f8;">{
    Receiver Receiver {get;set;}
    void Execute();
}
 
public class ConcreteCommand : ICommand
{
    public string Parameter { get; set; }
    Receiver  Receiver { get; set; }
    public ConcreteCommand(Receiver receiver)
    {
          this.Receiver = receiver;
    }
 
    public override void Execute()
    {
        this.Receiver.Action(Parameter);
    }
}
 
public class Receiver
{
    public void Action(string message)
    {
        Console.WriteLine("Action called with message, '{0}'.", message);
    }
}
   
public class Invoker
{
    public ICommand Command { get; set; }
 
    public void ExecuteCommand()
    {
        Command.Execute();
    }
}


Here the implementation has a ICommand interface which helps to encapsulate a command into it. The ConcreteCommand is an implementation of ICommand that could be used to encapsulate a method such that it can be invoked later. The reciever is an object that calls the Action method to be passed to the Command object. 

The Receiver actually holds the method Action which needed to be called when the Invoker invokes it to a Command. The Invoker holds the command object and executes the command. 

You can provide logic to queue Command objects inside the Invoker in a list, and call the Execute on each of the Commands one by one. 

In WPF, there is already a Command pattern implementation with ICommand interface.