Card 02/ 09
Command Pattern Structure: The Class and Sequence Diagrams
Invoker, Command, ConcreteCommand and Receiver, and who calls whom when the button is pressed.
Command has four participants and a client: the interface every command shares, the concrete command that knows what to do, the receiver that does the real work, and the invoker that triggers commands without knowing what they do. This card reads their roles off the Gang of Four's class diagram, then follows one press of a button through a sequence diagram.
| Participant | Role |
|---|---|
| Command | Declares execute, and undo when the commands can be reversed. |
| ConcreteCommand | Holds a receiver and the arguments of one request, and calls the receiver in execute. It stores whatever undo will need. |
| Receiver | Knows how to do the work, such as a document that inserts text. It knows nothing of commands. |
| Invoker | Asks a command to run, and may keep it in a history. It knows only the Command interface. |
| Client | Creates the concrete command, gives it its receiver, and hands it to the invoker. |
The invoker never touches the receiver: it holds a command and calls execute, and the command turns that into the real call. That separation is what lets one button class serve every action, and one history serve every kind of edit. Undo follows the same path in reverse: the invoker pops the last command and calls undo, and the command uses what it stored to put the receiver back.
← → move through sections and cards