The command pattern encapsulates method invocation in an object. It packages the requests, the receiver, and all the details needed to execute this request into a command object.
The command object has usually only one method, execute. We can then use the command object or pass it to other components in the system.
Callers trigger the execute method on the command object to invoke the actions on the receiver.
The command pattern is useful if you want to decouple components that require specific functionality from the method invocation details and the object which actually executes the actions.
The command pattern can be used to implement support for undo operations. Another frequent application of the pattern is creating macros.
A macro is a command which executes multiple commands on different receiver objects. Now let’s see how the command pattern works using the sequence diagram.
First, the client creates the command object. The command object packages the receiver and the set of actions required to execute a given request. Next, the client sets the command on the invoker by calling the invoker’s setCommand method. When the invoker needs to perform the given request, it simply invokes the command object’s execute method. After that, the invoker may discard the command or it can keep it for further use. Calling the command object’s execute method causes the invocation of the actions on the receiver.
The command design pattern encapsulates a request into an object. Invokers can call this command object to perform a request without knowing the details required to performthat operation or the receiver that will execute the operation.
- Define an interface with a method signature like
- Create derived classes that encapsulate subset of a “receiver” object, the method to invoke and the arguments to pass.
- Instantiate a Command object for each deferred execution request.
- Pass the Command object from the client to the invoker.
- The invoker decides when to perform action –
Summary: The command encapsulates method invocation, including all the details needed to perform the action. Callers can trigger the action at a later time without knowing the receiver or the actions that get executed behind the scenes. With this pattern, we decoupled the object that makes the request from the object that actually receives and executes the request. The command pattern is easy to implement.
Disadvantage: Exposing details of the receiver object or any information needed to perform the action to the component that is using the command object. You should also protect your command objects from concurrent access, as they may be used by multiple components and from different threads.