Java Reference
In-Depth Information
The C
OMMAND
pattern often names its standard operation
execute()
or
perform()
. But
nothing limits the operation to this name; nor is there a limitation that this pattern may use
only a single operation. In particular, instances of C
OMMAND
often include an
undo()
operation to reverse the effects of an
execute()
. In some cases, you may be able to
implement
undo()
, relying only on information in a command object. More often, you will
need to restore a complete system to the state it was in before a command executed.
CHALLENGE 24.6
Which pattern provides for the storage and restoration of an object's state?
Summary
The C
OMMAND
pattern lets you encapsulate a request in an object so that you can modify at
runtime the method that a client will call. A classic example of the usefulness of C
OMMAND
comes with menus. Menus know
when
to execute an action but don't know which method to
call. C
OMMAND
lets you parameterize a menu with the method calls that correspond to menu
labels.
When you use a Java menu you can supply commands into a context that other developers
have created. In other cases, you may take the role of the context provider, developing an
environment in which to execute commands. Your environment may allow for
parameterization of a service, as Java menus do. You may also provide hooks, or add extra
value, such as timing an operation.
C
OMMAND
fixes the signature of an operation and lets classes vary, applying this trick of
polymorphism to encapsulate an operation in an object. Perhaps because this idea is so
fundamental, C
OMMAND
has interesting relationships to many other patterns. C
OMMAND
can
be an alternative to M
EDIATOR
or T
EMPLATE
M
ETHOD
and often interacts with other
patterns.