Command Pattern

Command pattern is object behavioral design pattern that helps you handle different activities in application using same interface. I’m using Command Pattern in some of my systems to handle similar actions together and to split more comples operations to smaller steps by example. In this posting I will give you overview of Command Pattern.

Definition

Command Pattern encapsulates a request as an object, there by letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

p. 233, Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides.

Implementing Command Pattern

The diagram below shows one way how to implement Command Pattern in your code.

Command Pattern

Instead of defining interface for commands you can also use abstract base class that concrete command classes inherit. This is useful if you have some generic functionalities that all your commands use. Of course, you may also have base classes for groups of different commands. It’s really up to you to find out what makes best sense in your code.

Why Command Pattern?

The most important reasons to use Command Pattern are:

  • Command interface or base class breaks dependency between concrete command and caller – caller knows only interface or base class and therefore you can replace implementations of same command without affecting caller.
  • It is possible to create composite commands where one command contains subcommands it can run or execute.
  • Adding of new commands is easy as you have to implement command interface or extend abstract base command.

Example

You can use Command Pattern for different operations in your application. Suppose we have commands for updating customer bonus points and approving of orders. We define interface for command:

public interface ICommand

{

    void Execute();

}

Now we write two command implementations:

public class ImportOrdersCommand : ICommand

{ 

    public void Execute()

    {

        // Import orders from web store

        // Save orders

    }

}

 

public class GenerateInvoicesCommand : ICommand

{

    public void Execute()

    {

        // Load approved orders

        // Generate invoices

    }

}

Somewhere in code we can use these commands like this:

var commands = new Collection<ICommand>();

commands.Add(new ImportOrdersCommand());

commands.Add(new GenerateInvoicesCommand());

 

foreach (var command in commands)

{

    command.Execute();

}

If you need some decision making mechanism in commands flow you better convert your commands to workflow activities and go with Windows Workflow Foundation.

Wrapping up

Command Pattern helps you couple system logic to classes that have common interface or base class that decouples them from caller classes. It is easy to change or replace implementations of commands without changing code in callers. You can also build composite commands that contain sub-commands and it is also possible to use arrays of commands and execute them when needed. You can extend your commands the way you want – here I gave just simple example that communicates the point of Command Pattern the best.

Book recommendation! Those who want to find out more about design patterns and have a timeless hardcover handbook on the work desk should consider the book “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    2 thoughts on “Command Pattern

    Leave a Reply

    Your email address will not be published. Required fields are marked *