Published: 06 Oct 2008
By: Granville Barnett
Download Sample Code

In this part of the design patterns series we investigate the command pattern and its uses.

Contents [hide]

Introduction

The command pattern is interesting in that it’s the first pattern that we will have investigated that is concerned with actions. Specifically, the encapsulation of actions. This pattern provides the blueprint for us to encapsulate actions for both simple and advanced design scenarios.

Design Patterns Series

  • Part 1 Learn how to design more robust and maintainable code by incorporating design patterns into your software projects.
  • Part 2 This part shows the observer design pattern.
  • Part 3 In this part you will learn about the factory pattern.
  • Part 4 This part of the design patterns covers the singleton pattern.
  • Part 5 In this part of the design patterns series we investigate the command pattern and its uses.
  • Part 6 In this part of the design patterns series we will look at the adapter pattern.
  • Part 7 In this part of the design patterns series we will take a look at the template pattern.
  • The Command Pattern

    If there is one thing that you take out of this article it’s that the command pattern is concerned with encapsulating invocation. The invocation referring to a method which contains the necessary to perform one or more actions.

    Before we proceed any further we will take a little time to look at some key roles within the command pattern and discuss them. These key roles namely consist of an invoker, command, and receiver. In some descriptions of the command pattern you will also come across a client. We will return to the client and its role later on.

    The scenario

    Let us assume that you have just come home from work and within your household there are several people who all want you to do something. Now let us further assume that you are a pretty primitive person in that you can only remember one of the requested commands at any one time.

    To continue our analogy as you walk through the front door one of the members in the household requests that you turn on the hot water. The request requires you to go to the boiler and flip the switch so that everyone tonight can have a nice hot shower. If we pause for a slight moment here we can observe a few things about the scenario. We know that people can indeed perform various different tasks; we could further say that each task could be represented as a command. Just as we received a request to turn the hot water on, we may also have received a request from another member in the household to fix their computer.

    Turning the hot water on and fixing another members computer are commands that we have been assigned. As a person we know how to execute several commands each of which vary to some degree.

    Keep this scenario loaded in your mind for a few minutes.

    The invoker

    As the name implies one would expect the invoker to invoke, or trigger something. Our assumptions are indeed correct. The invoker has the responsibility of triggering the execution of a command, or possibly a number of commands.

    Using the scenario we described before, we, the Person are the invoker. We have the knowhow to perform various actions. Flipping the switch on the boiler to turn the hot water on is an action that we are fully capable of performing. Our skills don’t just stop there, we can perform many other actions, e.g. we can bring the washing in, or perhaps go do the shopping. The bounds of our capabilities are indeed limitless (well, nearly).

    The command

    In our example scenario the command is clear – switch the hot water on. The command requires us to perform an action. As we will see in the implementation the command not only encapsulates an action but also the receiver in which the action is to be performed upon (discussed later).

    A command typically contains the required within a method called Execute. This method will perform its actions upon the receiver provided.

    The receiver

    What is the thing that we have been requested to perform the action upon? In our example scenario the Boiler is the receiver. The command given to us therefore requires us to walk up to the Boiler and flip the hot water switch to its on state.

    The client

    It is the client who is in charge of setting the command and the receiver that the command should be performed upon. In our example scenario the member of the household who gave us our task could be the client. Of course we could have multiple clients.

    Putting it all together

    The following UML diagram shows our design. The client in the following diagram should be thought of in our example to be a pseudoname for the work done within the Main entry point method. That is we assign the command and its associated receiver to the Person object.

    Figure 1: Our design thus far

    Our design thus far

    Before we look at the code let’s just walk through this diagram quickly just to further clarify things. The client (Client being pseudeoname for the work done in the Main method in our example) defines a command (TurnOnHotWaterCommand) and also provides a receiver (Boiler) for that command. The invoker (Person) contains a command which is anything that implements ICommand. The command assigned to the Person via its Command property is fulfilled upon the invocation of the Request method.

    The multiplicities in the UML diagram only apply to our example. As we alluded to in passing earlier the invoker may be composed of many commands. Similarly the client may also assign several commands and associated receivers to the invoker.

    Listing 1: ICommand.cs

    Listing 2: Boiler.cs

    Listing 3: TurnHotWaterOnCommand.cs

    Listing 4: Person.cs

    Listing 5: Program.cs

    If you run the project then you will see the following (predicted) output:

    Figure 2: Output of the example

    Output of the example

    Why would I use this?

    Notice that the commands associated to the invoker are encapsulated; all the Person cares about is that the command associated to it implements the interface ICommand and thereby exposes an Execute method. Of course in this article we have covered a very simple example to accustom the reader with the design pattern, but what about having a queue of commands? If the invoker contained a queue (doesn’t have to be a queue) of commands to execute this would be pretty handy, after all, the invoker doesn’t know what its executing just that the commands implement ICommand.

    A common example raised when discussing the command pattern is the one of rehydrating queues of work items. As an example consider a queue that contains various commands to perform. There may arise a time when we want to temporarily cease to perform the remaining commands in the queue and persist them to a data store or to disk. When the appropriate time comes we can rehydrate the stored commands and continue performing them. This idea can be applied to many varying scenarios and is a nice application of the command pattern.

    The command pattern and delegates

    In .NET we can use delegates to achieve the behavior exhibited in the command pattern. Using delegates has certain advantages:

    • They get rid of boilerplate code
    • You can use succinct language features like lambda expressions to form commands
    • You can invoke delegates asynchronously out of the box
    • By using delegates you define the signature of the command. The following delegate for example will allow us to specify rudimentary commands.

    Using the above command prototype we can do things like assign arbitrary commands to a Person.

    Listing 6: Person.cs

    Listing 7: Program.cs

    You don’t have to go far to find a good example of such an approach, e.g. the System.Threading.ThreadPool’s QueueUserWorkItem method allows you to assign multiple units of work that will be carried out on threads available in the thread pool.

    Summary

    In this article we have looked at the command pattern, a pattern concerned with the encapsulation of invocation. We have discussed the roles of the command, receiver, invoker, and client. Moreover, we have also looked at the relationship between each of the respective roles in the command pattern culminating in the implementation of a simple example scenario. Finally we deviated and looked at how delegates in .NET can be used to achieve a similar result that doesn’t rely on interfaces.

    Acknowledgements

    I would like to thank Jon Skeet [1] for reviewing this article and providing some more insight on the command pattern in relation to .NET.

    [1] http://msmvps.com/blogs/jon_skeet

    <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Granville Barnett

    Sorry, no bio is available

    This author has published 32 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Introduction to StructureMap
    Have you heard of StructureMap, generally know what it’s for, and want to know how to get started qu...
    DI Patterns: Constructor Injection
    In this article, an excerpt from the book "Dependency Injection in .NET", we will take a detailed lo...
    The Command Pattern
    In this article I will provide a quick refresher on what the command pattern is used for, how it wor...
    TypeMock’s Arrange-Act-Assert
    Brian Mains discusses how to implement the Arrange-Act-Assert pattern in TypeMock.
    Key Process Patterns
    This article, based on chapter 2 of Specification by Example, presents effective patterns for softwa...

    You might also be interested in the following related blog posts


    Learn design patterns from real projects: JBoss case study (Part 1). read more
    Designing a Windows 8 Metro style app starting from an existing Windows Phone app Design Case Study Part 1 read more
    Oredev Wrap-Up read more
    Introducing SharePoint 2010 Training at U2U read more
    The Underground at PDC read more
    12 ASP.NET MVC Best Practices read more
    Screencast Whats new in the Entity Data Model Designer in VS2010 read more
    What needed to be monitored to get better Governance read more
    SharePoint 2010 Workflow read more
    Formatting Text in RadControls for WinForms Q3 2009 read more
    Top
     
     
     

    Discussion


    Subject Author Date
    placeholder missing images Eduard-Cristian Stefan 10/7/2008 11:44 AM
    RE: missing images Sonu Kapoor 10/7/2008 11:53 AM
    placeholder Separate "what" from "how" Udi Dahan 10/9/2008 12:45

    Please login to rate or to leave a comment.