|
| 1 | +# Command Pattern |
| 2 | + |
| 3 | +Encapsulate a request as a stand-alone object, which can be used to |
| 4 | +- parameterize clients with different requests |
| 5 | +- queue or log requests |
| 6 | +- support undoable operations |
| 7 | + |
| 8 | +## Problem |
| 9 | + |
| 10 | +- Coupling the invoker of a request to a particular request should be avoided. |
| 11 | + |
| 12 | +## Solution |
| 13 | + |
| 14 | +- Define separate `Command` objects that encapsulate a request. |
| 15 | +- A class delegates a request to a command object instead of implementing a particular request directly. |
| 16 | + |
| 17 | +## Common Structure |
| 18 | + |
| 19 | + |
| 20 | +*Source: Refactoring.Guru* |
| 21 | + |
| 22 | +* Command |
| 23 | + * declares an interface for executing an operation |
| 24 | +* ConcreteCommand |
| 25 | + * defines a binding between a Receiver object and an action. |
| 26 | + * implements `Execute` by invoking the corresponding operation(s) on Receiver. |
| 27 | +* Client |
| 28 | + * creates a ConcreteCommand object and sets its receiver and params. |
| 29 | +* Invoker |
| 30 | + * asks the `Command` to execute the request. |
| 31 | +* Receiver |
| 32 | + * knows how to perform the operations. Any class may serve as Receiver. |
| 33 | + |
| 34 | +## Collaboration |
| 35 | + |
| 36 | + |
| 37 | +*Source: http://www.cs.mcgill.ca* |
| 38 | + |
| 39 | +* When commands are undoable, ConcreteCommand stores state for undoing the command prior to invoking `Execute`. |
| 40 | + |
| 41 | +## Benefits |
| 42 | + |
| 43 | +* Decouples classes that invoke operations from the one that knows how to perform it. |
| 44 | +* Extensibility: Commands are first-class objects. They can be manipulated and extended. It is easy to add new commands. |
| 45 | +* Allows assembling simple commands into larger ones --> composite command |
| 46 | + |
| 47 | +## Drawbacks |
| 48 | + |
| 49 | +* Increases overall code complexity by creating multiple additional classes. |
| 50 | + |
| 51 | +## Example |
| 52 | + |
| 53 | +**Definition** |
| 54 | + |
| 55 | +**Usage** |
| 56 | + |
| 57 | +## Comparison with other patterns |
| 58 | + |
| 59 | +* **Memento** can keep state the command requires to undo its effect. |
| 60 | + |
| 61 | +* **Composite** can be used to implement MacroCommands. |
| 62 | + |
| 63 | +* **Prototype** can help when you need to save copy of the Command into history. |
| 64 | + |
| 65 | +* **Chain of Responsibility** passes a request sequentially along a dynamic chain of receivers. Command establishes a *one-directional* connection from senders to receivers. |
| 66 | + |
| 67 | +* **Mediator** has senders and receivers reference each other indirectly. |
| 68 | +Command holds the reference of a receiver only. |
| 69 | + |
| 70 | +* **Observer** passes a request to all receivers *at the same time* but allows them to subscribe and unsubscribe from receiving further requests dynamically. |
0 commit comments