Cheatsheet
Command
Intent
Put an action and its data inside an object, so whoever triggers it doesn't need to know how it's done and it can be stored, queued, logged or undone.
Structure (UML)
classDiagram
direction LR
class DeskCommands {
<<Client>>
+book(session, athlete) Command
+cancel(session, athlete) Command
+move(athlete, from, to) Command
}
class FrontDesk {
<<Invoker>>
+run(Command command) String
+undo() String
}
class Command {
<<Command>>
+execute() void
+undo() void
+describe() String
}
class BookCommand {
<<ConcreteCommand>>
}
class CancelCommand {
<<ConcreteCommand>>
}
class MoveCommand {
<<ConcreteCommand>>
}
class ClassRoster {
<<Receiver>>
+book(session, athlete) void
+cancel(session, athlete) int
+restore(session, index, athlete) void
}
FrontDesk o-- Command : history
Command <|.. BookCommand
Command <|.. CancelCommand
Command <|.. MoveCommand
DeskCommands ..> Command : creates
BookCommand --> ClassRoster
CancelCommand --> ClassRoster
MoveCommand --> ClassRosterParticipants
- Command (Command), the interface with execute(), undo() and describe()
- ConcreteCommand (BookCommand, CancelCommand, MoveCommand), each action with its data and its own way to undo itself
- Receiver (ClassRoster), which knows how to do the real work
- Invoker (FrontDesk), which runs the commands, keeps the history and undoes
- Client (DeskController with DeskCommands), which creates each command with its receiver and its data
Command.java
/** An action at the front desk, packed into an object: it can be run, undone and described. */
public interface Command {
void execute();
void undo();
String describe();
}Pros
- Undo, logging and queuing all live in one place, the invoker
- Whoever runs them knows no concrete action, so adding one doesn't touch it
- Each action and how to undo it live together, in a small class
Cons
- One class per action, which can be a lot for simple things
- Undoing properly means saving what's needed (the spot, the original class…) and it's easy to forget something
- If others change the state outside the history, undoing may stop making sense