In programming, we are usually need to queue requests, or decouple implementation of requests from its caller. And this is reason Command pattern was given birth. The Command pattern, basically, allows us encapsulate commands into objects. Thereby, it provides some useful options, such as:
- Queue or dequeue requests
- Parameterize client with different requests
- Support redo/undo functionality
The implementation of Command pattern is quite simple with four major terms: Receiver, Invoker, Command, ConcreteCommand and Client. Let take a look at bellow diagram:
Look through this diagram we can see that the Command interface is heart of this pattern which declares an interface to execute operations. Each ConcreteCommand class extends from this interface and keeps an instance of Receiver which knows exactly how to execute action. This Receiver object provides implementations of perform method to execute command’s action.
- Client: create Receiver, Invoker and ConcreteCommand, then add these concrete commands to Invoker and execute them.
- Command: define the common interface of requests.
- ConcreteCommand: extends from Command interface, keeps instance variable of Receiver. It implements inherited method by call variants of action of Receiver object.
- Invoker: carries out the requests.
- Receiver: knows exactly how to perform the actions.
Look at the diagram we can found that the biggest advantage of Command pattern is decoupling Invoker from Receiver, separating completely the sender and executor.
To move deeply into the pattern, I am developing a demo of undoable functionality, a Calculator demo application. Basically, to implement a system that supports undo/redo function we have two options:
- Store a snapshots of whole system before executing an action. So that we can rollback this version of system later. This option clearly required a lot of memory but less of implementing code.
- Store the performed actions. Beside we need to implement inverse action to undo the performed actions latter.
In scope of this post, I decide to implement the demo base on second option, storing performed action. You can download full source here.
The heart of undo/redo functionality is Calculator class( Invoker). This class contains two stacks of Command which implement algorithm for redoing and undoing.
We also have two concrete classes, AddCommand and MinusCommand. Their jobs are executing plussing and substracting.
That is what we need to know about Command pattern. If there any question about the pattern or source code, please free to comment on this post.