What is a Command Pattern?
Command Design Pattern is a pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters. This helps you to have loose coupling between the invoker and the receiver.
The invoker does not need to know the receiver. And both can be updated individually, as long as the contract is maintained.
Advantages of Command Design Pattern
- It allows you to convert a method call into individual object giving you the flexibility to use it in parameters.
- It allows you to queue operations, schedule invocations or reverse operations..
- It embodies the single responsibility design principle, since one command class is responsible for a single action.
Disadvantages of Command Design Pattern
- The application size can increase a lot as you can have many small command classes.
- Command Interface – for declaring an operation
- Concrete Command classes – Extends the command interface and invokes the business logic on the receiver.
- Invoker – Which calls the operation.
- Receiver – Executes the operation.
In the above diagram, we have the Device as the interface. Television is the receiver class. TurnTVOn and TurnTVOff are the command classes. Invoker class is not present in the UML diagram. It would be the class from which the method execute is called (e.g. Remote Class)
Let us take an example. We want to write a function for a Remote, such that each button takes in the device it is supposed to operate on. We use the command pattern for this. For the sake of keeping this example simple, we have only two functions being supported by the remote,
off. And we only have the TV to operate on.
First let us define the device interface and the device implementations. In this example that would be the Television class.
Next we define the Command interface.
Next let us implement the two commands
Let us define the
Remote class. The Remote class does not need to be aware of which device it is working on.
Bringing it all together in Main.
The Command pattern implementation allows you to keep a stack of commands and help undo/redo the actions executed. Its a pattern that is widely used in applications that have a GUI, for example, your text editor apps.