Command
Intent
Encapsulate a request as an object, thereby letting you parameterize
clients with different requests, queue or log requests, and support
undoable operations.
Problem
Need to issue requests to objects without knowing anything about the
operation being requested or the receiver of the request.
Discussion
Command decouples the object that invokes the operation from the one
that knows how to perform it. To achieve this separation, the designer
creates an abstract base class that maps a receiver (an object) with an
action (a pointer to a member function). The base class contains an
execute() method that simply calls the action on the receiver.
All clients of Command objects treat each object as a "black box" by
simply invoking the object's virtual execute() method whenever the
client requires the object's "service".
Sequences of Command objects can be assembled into composite (or macro)
commands.
Structure
Example
The Command pattern allows requests to be encapsulated as objects,
thereby allowing clients to be parameterized with different requests.
The "check" at a diner is an example of a Command pattern. The waiter
or waitress takes an order or command from a customer and encapsulates
that order by writing it on the check. The order is then queued for a
short order cook. Note that the pad of "checks" used by each waiter is
not dependent on the menu, and therefore they can support commands to
cook many different items. [Michael Duell, "Non-software examples of
software design patterns", Object Magazine, Jul 97, p54]
Non-software example
Rules of thumb
Chain of Responsibility, Command, Mediator, and Observer, address how
you can decouple senders and receivers, but with different trade-offs.
Command normally specifies a sender-receiver connection with a
subclass.
Chain of Responsibility can use Command to represent requests as
objects. [GOF, p349].
Command and Memento act as magic tokens to be passed around and invoked
at a later time. In Command, the token represents a request; in
Memento, it represents the internal state of an object at a particular
time. Polymorphism is important to Command, but not to Memento because
its interface is so narrow that a memento can only be passed as a
value. [GOF, p346]
Command can use Memento to maintain the state required for an undo
operation. [GOF, p242]
MacroCommands can be implemented with Composite. [GOF, p242]
A Command that must be copied before being placed on a history list acts
as a Prototype. [GOF, p242]
POSA's Command Processor pattern describes the scaffolding Command needs
to support full multilevel undo and redo. [Vlissides, Java Report,
Nov 2000, p80]
Notes
"Memento-Command" - a new pattern by John Vlissides. Presented in
Java Report, November 2000, pp70-80. Intent: manage undo state
when a command can affect unforseen receivers.
C++ Demos | Java
Demos | Lab