The Command Pattern is a software design pattern that is used to encapsulate a request as an object. This pattern enables us to decouple the client that issues the request from the object that receives the request. The command pattern has four basic components:
Command: This is the interface that all commands implement.
Concrete Command: This class implements the Command interface and provides the necessary information to execute the command.
Receiver: This class contains the logic to execute the command.
Invoker: This class is responsible for executing the command.
An example of the Command Pattern is a media player application that has a play, pause, and stop button. When the user clicks on the play button, it sends a command object to the media player. The command object is responsible for telling the media player to play. The receiver is the media player object, and the invoker is the button handling the user input. The concrete commands are play, pause and stop which implements the command interface. With this pattern, each command can be executed in multiple ways, allowing the application to easily extend the actions performed by the buttons.
The key points of Command Pattern are:
What is the Command pattern and what problem does it solve?
Answer: The Command pattern is a design pattern that encapsulates an action as an object, allowing it to be decoupled from the object that requested it. It solves the problem of coupling the object that invokes an operation with the object that performs the operation.
How does the Command pattern differ from the Strategy pattern?
Answer: The Command pattern is focused on encapsulating an operation as an object that can be passed around, whereas the Strategy pattern is focused on encapsulating interchangeable algorithms that can be used to implement a specific behavior.
What are the four key components of the Command pattern?
Answer: The four key components of the Command pattern are the Command interface, the ConcreteCommand class(es), the Receiver object, and the Invoker object.
How does the Command pattern support undo/redo functionality?
Answer: By storing a history of executed commands, the Command pattern allows you to undo or redo previous actions by replaying or reversing individual commands from the history.
What are some common use cases for the Command pattern?
Answer: Some common use cases for the Command pattern include implementing menu items, toolbar buttons, and keyboard shortcuts in a graphical user interface, implementing multi-level undo/redo functionality, and implementing a transactional system for database updates.