Click here to Skip to main content
Click here to Skip to main content
Go to top

Command Design Pattern

, 4 May 2011
Rate this:
Please Sign up or sign in to vote.
Command Design Pattern clearly explained with an example.

You can see this and other great articles on Design Patterns here.

The Command Design Pattern allows you to store a list of actions that you can execute later. A common example is storing the undo actions in an application. The undo actions are stored as the user is making changes in an application. When the user decides to perform the undo, the undo actions are retrieved and executed.

The benefit of the Command Pattern is that it hides the details of the actions that needs to be performed, so that the client code does not need to be concerned about the details when it needs to execute the actions. The client code just needs to tell the application to execute the command that was stored.

In an undo example, if the user moved a rectangle from position X to position Y, then the undo action will be to move the rectangle from position Y back to position X. The details of this undo action are stored in the command objects so that when the user needs to execute the undo action, the application only needs to tell the command object to execute its action without knowing that it is supposed to move the rectangle from position Y back to position X.

The Command pattern is not focused so much on the sequence of the actions stored, but more on hiding the details of the action it needs to perform.

We will do an actual example of the Command Design Pattern to show you how it works. But for now, let’s look at the UML of the Command Design Pattern:

  • The ICommand interface defines the methods that all Command classes must implement.
  • The Command class stores the details of the actions that need to be performed (the location of position Y and position X for the undo).
  • The Receiver class performs the action when called upon (moving the rectangle from position Y back to position X).
  • The Invoker class stores the list of commands and can ask the ICommand to execute.
  • The Client class uses the Invoker to run the commands.

The client code (calling code) will used the Invoker to run the commands, where the Command objects will call the Receiver to perform the action. The benefit is that the client code does not need to know what is stored in the Command objects nor the actions that will be performed by the Receiver, and this is the key to the Command Design Pattern.

Now let’s do an example. In our example, we need to store some undo actions when the user is using the application, and when the user decides to perform the undo, we can just use the invoker to run the commands. Below is the UML for our undo example:

  • The UndoCommand class stores the location where the rectangle is supposed to move back.
  • The UndoPerformer will move the rectangle back to its original position, taking the UndoCommand as the parameter.
  • The Invoker stores the list of undo commands.

 

Below are the implementation code and the output of our example; notice that the client code does not need to know the details of the undo action when it needs to call it. The client code is simply:

invoker.RunCommand();
class Client
{
    static void Main(string[] args)
    {
        Invoker i = new Invoker();
        //save undo to position 100
        ICommand a = new UndoCommand(100);
        i.AddCommand(a);
        //save undo to position 200
        ICommand b = new UndoCommand(200);
        i.AddCommand(b);
        //perform the undo
        i.RunCommand();   //the client does not need to know about the details of the undo
    }
}

public interface ICommand
{
    void Execute();
}

public class UndoCommand : ICommand
{
    private int location;

    public int Location
    {
        get { return location; }
    }

    public UndoCommand(int originalLocation)
    {
        location = originalLocation;
    }

    public void Execute()
    {
        new UndoPerformer().Undo(this);
    }
}

public class Invoker
{
    private Stack<icommand> commandList = new Stack<icommand>();

    public void RunCommand()
    {
        while (commandList.Count > 0)
            commandList.Pop().Execute();
    }

    public void AddCommand(ICommand c)
    {
        commandList.Push(c);
    }
}

public class UndoPerformer
{
    public void Undo(ICommand c)
    {
        if (c is UndoCommand)
        {
            int originalLocation = (c as UndoCommand).Location;
            Console.WriteLine("Moving back to position: " + originalLocation);
        }
    }
}

Liked this article? You can see this and other great articles on Design Patterns here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DevLake

United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 3 PinmemberLivio Francescucci4-May-13 21:16 
GeneralMy vote of 5 PinmemberMC19727-Dec-11 4:21 
GeneralMy vote of 1 PinmemberBill SerGio, Infomercial King4-May-11 8:13 
GeneralRe: My vote of 1 PinmemberDaveAuld4-May-11 8:46 
GeneralRe: My vote of 1 PinmemberBill SerGio, Infomercial King4-May-11 8:59 
GeneralRe: My vote of 1 PinmemberDaveAuld4-May-11 9:03 
GeneralMy vote of 4 PinmemberAre Jay25-Apr-11 14:53 
GeneralNice Article PinmemberAre Jay25-Apr-11 14:51 
Thanks for the design pattern series.
 
I am looking of a pattern that has an implemention like the command pattern but the Execute() needs to handle:
- void
- String
- XmlDocument
- XDocument
- int
- bool
- etc...
 
Any helpful tips?
I'm listening but I only speak GEEK.

GeneralRe: Nice Article PinmemberJV999926-Apr-11 20:52 
GeneralRe: Nice Article PinmemberAre Jay27-Apr-11 6:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 4 May 2011
Article Copyright 2011 by DevLake
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid