Command< Computer Science Design Patterns
The command pattern is an object behavioural pattern that decouples sender and receiver. It can also be thought as an object-oriented equivalent of a call back method. Call back: It is a function that is registered to be called at a later point of time based on user actions.
Encapsulate the request for a service as an object.
- to parameterize objects with an action to perform
- to specify, queue, and execute requests at different times
- for a history of requests
- for multilevel undo/redo
- + abstracts executor of a service
- + supports arbitrary-level undo-redo
- + composition yields macro-commands
- - might result in lots of trivial command subclasses
The best example for this pattern is the graphical user interface. On most multidata interfaces, you have both a "New" menu and a "New" button with an icon like in Libre Office Writer. Both controls are connected to a command object, so the action is performed by the same code.
This pattern is dealing with the whole architecture of a program. It may have a substantial impact on the project.
If the code already exists, this pattern is very expensive.
This pattern is very expensive to maintain.
This pattern is very expensive to remove, too.
- Use the Command term to indicate the use of the pattern to the other developers.
Consider a "simple" switch. In this example we configure the Switch with two commands: to turn the light on and to turn the light off. A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light — the Switch in the following example turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its two parameters. For example, you could configure the Switch to start an engine.