Java Reference
In-Depth Information
A
MacroCommand
contains a list of subcommands. When the execute method is called, the
MacroCommand
forwards subcommands.
If the
MacroCommand
supports undo, all internal commands must support it as well. When undo is called, this call
must be forwarded to the children in the reverse order of the execute method.
Related Patterns
Related patterns include the following:
Composite (page 157) - Use the Composite pattern to implement
MacroCommands
.
Memento (page 88) - Keeps the state of the receiver within the command to support undoing a Command.
Prototype (page 28) - The Prototype pattern can be used to copy the command before placing it in the history
list.
Singleton (page 34) - In most applications, the history list is implemented as a Singleton.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a
RunPattern
class,
In the Personal Information Manager, users might want to update or modify information in their system. This
code demonstrates how the Command pattern can provide update and undo behavior for a location.
In this example, a pair of interfaces model the generic command behavior. The basic command action is defined
by the
execute
method in
Command
, while
UndoableCommand
extends this interface by adding undo and redo
methods.
Example 2.4
Command.java
1. public interface Command{
2. public void execute();
3. }
Example 2.5
UndoableCommand.java
1. public interface UndoableCommand extends Command{
2. public void undo();