The Command Pattern is used to encapsulate requests themselves into objects.
Suppose you have a request you want another object to issue without knowing anything about the operation being requested or about the interface of the receiver.
You may want to implement an undo feature without having to deal with large switch statements.
You may want to keep a queue or log of requests.
You may want to have different pre-existing object types with different interfaces be controlled with the same calls. You can't make them implement an interface, without having to change them.
1. We start by creating an Abstract Command class that has an execute() method. All Concrete Commands will then be able to be run by calling their execute() method. Note: For implementing undo, an unexecute() method is advisable.
2. We then create a Concrete Command class that will associate itself with the intended Receiver of the request.
This completes the basic Command Pattern. The ConcreteCommand.execute() can be called, serving as an adaptor between the calling class and the receiver.
We will continue our solution in the case of wanting to controll pre-existing objects with the same calls.
3. The next thing we do is to create the Invoker class, which will associate itself with a number of Concrete Commands. This class has the method calls that we will use whenever we want to make a request of the receiver. Each method calls one of the associated Concrete Commands.
4. The Client will instantiate the Receivers, Concrete Commands, and the Invoker.
A look at the Commmand Pattern:
Image from www.JavaWorld.com
A code example for using the Command Patter is in this zip file.
A diagram of the example:
Adaptor
Action
Transaction
Modified: 18-Feb-2004
Matthew S. Cote