Patterns for behaviour · Chapter 17

Command pattern

Turn each request into an object so it can be undone, redone, queued, logged or replayed. Java and Python code for undo/redo stacks and macros, plus how Command differs from Strategy and Memento.

IntermediateInterview priority: High40 min
On this page
  1. The problem: actions with nowhere to live
  2. The idea: make each request an object
  3. Build it: undo and redo with two stacks
  4. Queues, logs and remote execution
  5. Command, Strategy, Memento: how they differ
  6. When not to use it
  7. In the interview
  8. Quiz

The problem: actions with nowhere to live

A text editor can make text bold from a toolbar button, a keyboard shortcut and a menu item. The first version puts the work in each handler: the button's click handler edits the document, the shortcut handler does the same thing again, and so does the menu.

Three triggers, one action, and no undo

  1. In a text editor, “make it bold” can come from a toolbar button, a keyboard shortcut or a menu. And users expect undo. If every button does the work directly, undo has nowhere to live.

Then users ask for undo. Where does it go? Each handler changed the document directly and forgot what it did. To undo, something must remember what was done, to what, and how to reverse it, and the handlers have already returned. The same gap appears when product asks for "record a macro", "retry failed actions later" or "show an activity log".

The root cause: a request exists only as a method call in progress. Once the call returns, the request is gone.

The idea: make each request an object

The Command pattern wraps a request in an object with a method such as execute(). The object holds everything needed to perform the request later, and often to reverse it with undo(). The button, the shortcut and the menu no longer do the work; they each hold a command and call execute().

The invoker runs whatever command it was given

  1. The Command pattern turns each request into an object. A BoldCommand knows how to execute() and how to undo(). The button, called the invoker, just runs whatever command it was given.
RoleIn the editorResponsibility
Command (interface)CommandDeclares execute() and, if undo is supported, undo()
Concrete commandInsertCommand, DeleteCommandStores its parameters and what it needs to reverse itself; calls the receiver
ReceiverDocumentKnows how to do the real work (insert, delete)
InvokerToolbar button, HistoryTriggers commands; knows nothing about what they do
ClientEditor set-up codeCreates commands with their receiver and hands them to invokers

Because a request is now a value, you can keep it: push it on a stack, put it in a queue, write it to a log, or send it to another machine.

Build it: undo and redo with two stacks

Undo pops a command from the history and reverses it

  1. Every executed command is pushed onto a history stack. Undo pops the top command and calls its undo(). Redo pushes it back. That’s how every editor’s undo works.

The rules every editor follows:

  • Run: execute the command, push it on the undo stack, and clear the redo stack (a new action starts a new branch of history).
  • Undo: pop from the undo stack, call undo(), push onto the redo stack.
  • Redo: pop from the redo stack, call execute() again, push back onto the undo stack.
  • Limit the undo stack (say 100 entries) so memory doesn't grow forever.

Each command stores exactly what it needs to reverse itself. An insert knows its position and text, so undo deletes that many characters. A delete can't know what it removed until it runs, so execute() saves the removed text for undo().

import java.util.*;

// The receiver: knows how to do the real work
class Document {
    private final StringBuilder text = new StringBuilder();
    String text() { return text.toString(); }
    void insert(int pos, String s) { text.insert(pos, s); }
    String delete(int pos, int len) {
        String removed = text.substring(pos, pos + len);
        text.delete(pos, pos + len);
        return removed;
    }
}

// The command interface
interface Command {
    void execute();
    void undo();
}

// Concrete commands: each stores what it needs to reverse itself
class InsertCommand implements Command {
    private final Document doc;
    private final int pos;
    private final String s;
    InsertCommand(Document doc, int pos, String s) { this.doc = doc; this.pos = pos; this.s = s; }
    public void execute() { doc.insert(pos, s); }
    public void undo()    { doc.delete(pos, s.length()); }
}

class DeleteCommand implements Command {
    private final Document doc;
    private final int pos, len;
    private String removed;                               // filled in by execute()
    DeleteCommand(Document doc, int pos, int len) { this.doc = doc; this.pos = pos; this.len = len; }
    public void execute() { removed = doc.delete(pos, len); }
    public void undo()    { doc.insert(pos, removed); }
}

// A macro: several commands that run and undo as one
class MacroCommand implements Command {
    private final List<Command> steps;
    MacroCommand(List<Command> steps) { this.steps = List.copyOf(steps); }
    public void execute() { steps.forEach(Command::execute); }
    public void undo() {                                  // reverse order
        for (int i = steps.size() - 1; i >= 0; i--) steps.get(i).undo();
    }
}

// The invoker: runs commands and keeps the history
class History {
    private final Deque<Command> undoStack = new ArrayDeque<>();
    private final Deque<Command> redoStack = new ArrayDeque<>();
    private final int limit;

    History(int limit) { this.limit = limit; }

    void run(Command c) {
        c.execute();                       // execute first: a failed command is not recorded
        undoStack.push(c);
        if (undoStack.size() > limit) undoStack.removeLast();   // forget the oldest
        redoStack.clear();                 // a new action ends the redo branch
    }

    boolean undo() {
        Command c = undoStack.poll();
        if (c == null) return false;
        c.undo();
        redoStack.push(c);
        return true;
    }

    boolean redo() {
        Command c = redoStack.poll();
        if (c == null) return false;
        c.execute();
        undoStack.push(c);
        return true;
    }
}

public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        History history = new History(100);

        history.run(new InsertCommand(doc, 0, "Hello world"));
        history.run(new DeleteCommand(doc, 5, 6));            // remove " world"
        history.run(new InsertCommand(doc, 5, ", Byte City"));
        System.out.println(doc.text());                       // Hello, Byte City

        history.undo();  System.out.println(doc.text());      // Hello
        history.undo();  System.out.println(doc.text());      // Hello world
        history.redo();  System.out.println(doc.text());      // Hello

        history.run(new MacroCommand(List.of(
            new InsertCommand(doc, 0, "> "),
            new InsertCommand(doc, 7, "!"))));
        System.out.println(doc.text());                       // > Hello!
        history.undo();  System.out.println(doc.text());      // Hello
    }
}

The MacroCommand is itself a Command holding a list of commands (a use of the Composite pattern), so "record a macro" and "undo the whole macro in one step" come for free. Its undo runs in reverse order: the last change is reversed first, just as you take off shoes before socks.

Two ways to undo

ApproachHow undo worksGood atWeak at
Inverse operation (above)Each command knows how to reverse itselfSmall memory per step; fastEvery command needs a correct inverse; some have none
Snapshot (Memento)Save the state before executing; undo restores itSimple and always correctMemory: a 5 MB document × 100 steps is 500 MB

Real editors mix them: inverse operations for typing, snapshots (or copy-on-write structures) for big changes like "apply filter to the whole image".

Queues, logs and remote execution

Once a request is an object, when and where it runs is a separate decision.

// A Runnable is a command with execute() named run()
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> mailer.sendInvoice("order-42"));    // queued, run later on another thread

// For a durable queue, the command must be plain data, not a lambda
record SendInvoice(String orderId) {}                // serialised to JSON, e.g. {"orderId":"order-42"}
queue.publish("jobs.send-invoice", json.write(new SendInvoice("order-42")));

Requests as objects: queued, sent, replayed

  1. Because requests are now objects, you can also store them, queue them to run later, send them to another machine, or replay them. Job queues, macros, database transactions and smart-home routines all use this idea.

The same idea runs through system design: a job in a message queue, an entry in a database's write-ahead log that is replayed after a crash, an event in an event-sourced system, and a Redux action in a front end are all commands stored as data. Job systems such as Celery and Sidekiq store a task name plus its arguments, exactly like the SendInvoice record.

Command, Strategy, Memento: how they differ

CommandStrategyMemento
The object representsA request: do this, to that, with these valuesA way of doing a jobA saved state of another object
HoldsReceiver and parameters, often undo dataOnly the algorithm (and its configuration)A snapshot, opaque to everyone but its owner
Who calls it, whenAn invoker, possibly later, on another thread or machineThe context, right now, as part of its own workThe owner, when it restores itself
Can be undone, queued, logged?Yes, that is the pointNo; it has no meaning outside its contextIt is the undo data
ExampleDeleteCommand(doc, 5, 6)PricingStrategy.price(cart)doc.save() → doc.restore(m)

The two are easy to confuse because both put behaviour in an object. A quick test: does the object make sense on its own, as a record of something to be done? DeleteCommand(doc, 5, 6) does. A WeekendPricing strategy does not; it is meaningless until a context hands it a cart.

When not to use it

In the interview

Your turn: a smart-home remote

A remote has 6 programmable slots, each with an "on" and "off" button, plus one global "undo" button that reverses the last button pressed. Devices: Light (on, off), Thermostat (setTemperature(int)), Speaker (on, off, setVolume(int)). A "movie night" slot should dim lights, set the speaker to 30 and the thermostat to 21 °C. Sketch the classes and how undo works for the thermostat.

Compare with our answer
interface Command { void execute(); void undo(); }

class SetTemperature implements Command {
    private final Thermostat t; private final int target; private int previous;
    SetTemperature(Thermostat t, int target) { this.t = t; this.target = target; }
    public void execute() { previous = t.temperature(); t.setTemperature(target); }
    public void undo()    { t.setTemperature(previous); }
}

class Remote {
    private final Command[] on = new Command[6], off = new Command[6];
    private Command last = new NoOp();
    Remote() { Arrays.fill(on, new NoOp()); Arrays.fill(off, new NoOp()); }   // empty slots do nothing
    void assign(int slot, Command onCmd, Command offCmd) { on[slot] = onCmd; off[slot] = offCmd; }
    void pressOn(int slot)  { on[slot].execute();  last = on[slot]; }
    void pressOff(int slot) { off[slot].execute(); last = off[slot]; }
    void pressUndo()        { last.undo(); last = new NoOp(); }
}

remote.assign(0,
    new Macro(List.of(new DimLights(light, 20), new SetVolume(speaker, 30), new SetTemperature(thermo, 21))),
    new Macro(List.of(new LightOn(light), new SpeakerOff(speaker))));
class SetTemperature(Command):
    def __init__(self, t: Thermostat, target: int):
        self.t, self.target, self.previous = t, target, None
    def execute(self) -> None:
        self.previous = self.t.temperature
        self.t.set_temperature(self.target)
    def undo(self) -> None:
        self.t.set_temperature(self.previous)

class Remote:
    def __init__(self):
        self.on: list[Command] = [NoOp()] * 6
        self.off: list[Command] = [NoOp()] * 6
        self.last: Command = NoOp()
    def assign(self, slot: int, on_cmd: Command, off_cmd: Command) -> None:
        self.on[slot], self.off[slot] = on_cmd, off_cmd
    def press_on(self, slot: int) -> None:
        self.on[slot].execute(); self.last = self.on[slot]
    def press_off(self, slot: int) -> None:
        self.off[slot].execute(); self.last = self.off[slot]
    def press_undo(self) -> None:
        self.last.undo(); self.last = NoOp()

remote.assign(0,
    Macro([DimLights(light, 20), SetVolume(speaker, 30), SetTemperature(thermo, 21)]),
    Macro([LightOn(light), SpeakerOff(speaker)]))

A strong answer mentions: the remote (invoker) knows only Command · each device is a receiver · undo for settings stores the previous value at execute time, not at construction · "movie night" is a macro command undone in reverse · a NoOp command for empty slots instead of null checks.

Your turn: the requirement changes

The smart-home company now wants routines that run on a schedule ("7:00 every weekday: lights on, thermostat 20 °C"), survive a server restart, and run on the hub in each home rather than on the server. Your commands currently hold direct references to Light and Thermostat objects. What has to change?

Compare with our answer

A strong answer mentions: commands must become serialisable data (type, device id, parameters) rather than objects holding live references · a registry on the hub that turns a device id into the receiver · persisting scheduled commands (database or durable queue) so restarts don't lose them · idempotent handling with a command id, since a message may be delivered twice · what undo means for a scheduled routine (probably none, or an explicit "revert" routine) · reporting results back to the server.

Command on one page
  • Intent: turn a request into an object so it can be stored, queued, logged, sent, undone and redone.
  • Roles: command interface · concrete commands (parameters + undo data) · receiver (does the work) · invoker (triggers) · client (wires them).
  • Undo/redo: run → push undo, clear redo · undo → pop, undo(), push redo · redo → pop, execute(), push undo · cap history.
  • Undo styles: inverse operations (small, needs a correct inverse) vs snapshots/Memento (simple, memory-hungry).
  • Macro: a command holding commands; undo in reverse; roll back on partial failure.
  • Lightweight form: Runnable, lambdas, Python callables, functools.partial. Durable queues need commands as data.
  • Not Strategy: a command is a request that makes sense on its own; a strategy is a way of doing the context's job now.
  • Watch for: external side effects (compensate), at-least-once delivery (idempotency), history memory.
Interactive labPractise it: wire buttons to commands and make undo workOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. A drawing app needs undo and redo for move, resize and recolour actions, triggered from menus, shortcuts and a touch bar. Which design fits best?

2. A user types A, B and C, undoes twice, then types D. What should redo do now?

3. A DeleteCommand saves the deleted text in its constructor, before execute() runs. Later, undo puts back the wrong text. Why?

4. What is the clearest difference between Command and Strategy?

5. A queue worker runs ChargeCardCommand, the call times out, and the queue redelivers the message. The customer is charged twice. What is the best fix?

6. An editor keeps a full copy of a 5 MB document before each command for undo, with a 100-step history. What is the main problem, and a common fix?

7. A "movie night" macro runs three commands; the third throws. What should MacroCommand.execute() do?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.