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)

Spring contextFront deskBookCommand«i»CommandDeskControllerCancelCommand30ClassRosterMoveCommandFrontDeskundo history

Participants

  • 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

← Command · Run it