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
Sometime it’s necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.
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.
- Declares an interface for executing an operation
- Define a binding between a receiver object and action
- Implements execute by invoking the corresponding operation on receiver
- Creates a ConcreteCommand object abd sets its receiver
- Ask the command to carry out the request’
- Knows how to perform the operation associated with carrying out a request. Any class may serve as the receiver.
- 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.
The command pattern has the following consequences,
- Command decouples the object that invokes the operation from that one that knows how to perform it.
- Commands are first class objects. They can manipulate and extended like any other object.
- You can assemble commands into a composite command. An example is the MicroCommand class. In general , composite commands are an instance of composite pattern.
- It’s easy to add new commands , because you don’t have to change existing classes.