Click here to Skip to main content
11,581,982 members (75,145 online)
Click here to Skip to main content

Command Design Pattern

, 4 May 2011 CPOL 25K 24
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

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 3 Pin
Livio Francescucci4-May-13 21:16
memberLivio Francescucci4-May-13 21:16 
GeneralMy vote of 5 Pin
MC19727-Dec-11 4:21
memberMC19727-Dec-11 4:21 
GeneralMy vote of 1 Pin
Bill SerGio, Infomercial King4-May-11 8:13
memberBill SerGio, Infomercial King4-May-11 8:13 
GeneralRe: My vote of 1 Pin
DaveAuld4-May-11 8:46
memberDaveAuld4-May-11 8:46 
GeneralRe: My vote of 1 Pin
Bill SerGio, Infomercial King4-May-11 8:59
memberBill SerGio, Infomercial King4-May-11 8:59 
GeneralRe: My vote of 1 Pin
DaveAuld4-May-11 9:03
memberDaveAuld4-May-11 9:03 
GeneralMy vote of 4 Pin
Are Jay25-Apr-11 14:53
memberAre Jay25-Apr-11 14:53 
GeneralNice Article Pin
Are Jay25-Apr-11 14:51
memberAre Jay25-Apr-11 14:51 
GeneralRe: Nice Article Pin
JV999926-Apr-11 20:52
memberJV999926-Apr-11 20:52 
GeneralRe: Nice Article Pin
Are Jay27-Apr-11 6:31
memberAre Jay27-Apr-11 6:31 
Thank you for the help, I will look at combining the two patterns.

Details:
I am using MEF to loosely couple my API so I can extend the business logic of the API (a plug and play feel).
So, the API is the host and it using the ExportMetadata Attributes of the Module (plugin, extension, etc.) to determine how to the module is to be treated.
Examples of ExportMetadata Attributes:
- Pre
- Post
- InsteadOf
- Default
** an Aspect Orientated approach to implementing the Modules.

So, the API is using a series of Controller objects to determine how the 'extended' Module should behave within the API...

Now to the original meaning of my initial question...

these controllers are passing around the Lazy<T, TMetadata> object imported to determine it's behavior
public class GenericController<T>
{
        private bool _isDefault = false;
	private IEnumerable<Lazy<T, IExtensionMetadata>> _imports { get; set; }	
		
	public Lazy<T, IExtensionMetadata> Execute { get; private set; }
	public IEnumerable<Lazy<T, IExtensionMetadata>> PreExecute { get; private set; }
	public IEnumerable<Lazy<T, IExtensionMetadata>> PostExecute { get; private set; }
 
	public GenericController(IEnumerable<Lazy<T, IExtensionMetadata>> imports, bool defaultOnly) : this( imports )
	{ this._isDefault = defaultOnly; }
 
	public GenericController(IEnumerable<Lazy<T, IExtensionMetadata>> imports)
	{ this._imports = imports; this.Init(); }
 
	void Init()
	{
		// process business rules of modules
	}
}

So when implementing the GenericConroller
...
String result = String.Empty;
GenericController<ArchivableDocument_Add> controller =
	new GenericController<ArchivableDocument_Add>(this._add);
foreach (var pre in controller.PreExecute)
	pre.Value.Add(userName, objectType, objectId, caption, url, messageId, taskId);
 
result = controller.Execute.Value.Add(userName, objectType, objectId, caption, url, messageId, taskId);
 
foreach (var post in controller.PostExecute)
	post.Value.Add(userName, objectType, objectId, caption, url, messageId, taskId);
 
return result;
...

Execution happens outside the contoller because:
- I may or may not have a return type
- Executing method signatures will alway be different
Ideally I'd like it to be as follows:
...
GenericController<ArchivableDocument_Add> controller =
	new GenericController<ArchivableDocument_Add>(this._add);
 
controller.Execute();
 
return conroller.Result as String;
...

Thoughts?
I'm listening but I only speak GEEK.

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 | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 4 May 2011
Article Copyright 2011 by DevLake
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid