Command Design Pattern

 definition
 UML diagram
 participants
 sample code in C#



definition

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Frequency of use:   medium high

UML class diagram


participants

    The classes and/or objects participating in this pattern are:

  • Command  (Command)
    • declares an interface for executing an operation
  • ConcreteCommand  (CalculatorCommand)
    • defines a binding between a Receiver object and an action
    • implements Execute by invoking the corresponding operation(s) on Receiver
  • Client  (CommandApp)
    • creates a ConcreteCommand object and sets its receiver
  • Invoker  (User)
    • asks the command to carry out the request
  • Receiver  (Calculator)
    • knows how to perform the operations associated with carrying out the request.

sample code in C#

This structural code demonstrates the Command pattern which stores requests as objects allowing clients to execute or playback the requests.

Show code

// Command pattern -- Structural example




This real-world code demonstrates the Command pattern used in a simple calculator with unlimited number of undo's and redo's. Note that in C#  the word 'operator' is a keyword. Prefixing it with '@' allows using it as an identifier.

Show code

// Command pattern -- Real World example




This .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features, such as, generics, reflection, object initializers, automatic properties, etc.

Show code

// Command pattern -- .NET optimized




   Better Code 
   Better Career 
   Better Lifestyle 


.NET
Design Pattern
Framework 4.0


 
C# and VB.NET


   Includes:

  Gang of Four Patterns
  Head First Patterns
  Enterprise Patterns
  SOA Patterns

  WPF Best Practices
  WCF Best Practices
  LINQ Best Practices

  Model View Controller
  Model View Presenter
  Model View ViewModel

  Much more...

Click here for details

-- Instant Access --
Instant Download