Command – Object Behavioral

Intent

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

Also Known As

Action, Transaction

Motivation

Sometime it’s necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.

Applicability

Use command pattern when you want to,

  • Parameterize objects by an action to perform.
  • Specify Queue and execute requests at a different time.
  • Support undo action
  • Support logging changes
  • Structure a system  around high-level operations built on primitive operations.

Structure

command pattern structure
command pattern structure

 

Participants

  • Command
    • Declares an interface for executing an operation
  • ConcreteCommand
    • Define a binding between a receiver object and action
    • Implements execute by invoking the corresponding operation on receiver
  • Client
    • Creates a ConcreteCommand object abd sets its receiver
  • Invoker
    • Ask the command to carry out the request’
  • Receiver
    • Knows how to perform the operation associated with carrying out a request. Any class may serve as the receiver.

Collaborations

  • The client creates a ConcreteCommand objects and specifies its receiver.
  • An Invoker object stores the ConcreteCommand object
  • The invoker issues a request by calling Excecute command. When commands are undoable, ConcreteCommand stores state for undoing the command prior to invoking Execute.
Command pattern collaboration
Command pattern collaboration

 

Consequences

The command pattern has the following consequences,

  1. Command decouples the object that invokes the operation from  that one that knows how to perform it.
  2. Commands are first class objects. They can manipulate and extended like any other object.
  3. You can assemble commands into a composite command. An example is the MicroCommand class. In general , composite commands are an instance of composite pattern.
  4. It’s easy  to add new commands , because  you don’t  have to change existing classes.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s