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.
On this page
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
- 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
- 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.
| Role | In the editor | Responsibility |
|---|---|---|
| Command (interface) | Command | Declares execute() and, if undo is supported, undo() |
| Concrete command | InsertCommand, DeleteCommand | Stores its parameters and what it needs to reverse itself; calls the receiver |
| Receiver | Document | Knows how to do the real work (insert, delete) |
| Invoker | Toolbar button, History | Triggers commands; knows nothing about what they do |
| Client | Editor set-up code | Creates 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
- 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
}
}from abc import ABC, abstractmethod
from collections import deque
class Document: # the receiver
def __init__(self):
self._text = ""
@property
def text(self) -> str:
return self._text
def insert(self, pos: int, s: str) -> None:
self._text = self._text[:pos] + s + self._text[pos:]
def delete(self, pos: int, length: int) -> str:
removed = self._text[pos:pos + length]
self._text = self._text[:pos] + self._text[pos + length:]
return removed
class Command(ABC): # the command interface
@abstractmethod
def execute(self) -> None: ...
@abstractmethod
def undo(self) -> None: ...
class InsertCommand(Command):
def __init__(self, doc: Document, pos: int, s: str):
self.doc, self.pos, self.s = doc, pos, s
def execute(self) -> None:
self.doc.insert(self.pos, self.s)
def undo(self) -> None:
self.doc.delete(self.pos, len(self.s))
class DeleteCommand(Command):
def __init__(self, doc: Document, pos: int, length: int):
self.doc, self.pos, self.length = doc, pos, length
self.removed = "" # filled in by execute()
def execute(self) -> None:
self.removed = self.doc.delete(self.pos, self.length)
def undo(self) -> None:
self.doc.insert(self.pos, self.removed)
class MacroCommand(Command): # several commands as one
def __init__(self, steps: list[Command]):
self.steps = list(steps)
def execute(self) -> None:
for step in self.steps:
step.execute()
def undo(self) -> None:
for step in reversed(self.steps): # reverse order
step.undo()
class History: # the invoker
def __init__(self, limit: int = 100):
self._undo: deque[Command] = deque(maxlen=limit) # oldest dropped automatically
self._redo: list[Command] = []
def run(self, cmd: Command) -> None:
cmd.execute() # a failed command is not recorded
self._undo.append(cmd)
self._redo.clear() # a new action ends the redo branch
def undo(self) -> bool:
if not self._undo:
return False
cmd = self._undo.pop()
cmd.undo()
self._redo.append(cmd)
return True
def redo(self) -> bool:
if not self._redo:
return False
cmd = self._redo.pop()
cmd.execute()
self._undo.append(cmd)
return True
doc, history = Document(), History(limit=100)
history.run(InsertCommand(doc, 0, "Hello world"))
history.run(DeleteCommand(doc, 5, 6)) # remove " world"
history.run(InsertCommand(doc, 5, ", Byte City"))
print(doc.text) # Hello, Byte City
history.undo(); print(doc.text) # Hello
history.undo(); print(doc.text) # Hello world
history.redo(); print(doc.text) # Hello
history.run(MacroCommand([InsertCommand(doc, 0, "> "), InsertCommand(doc, 7, "!")]))
print(doc.text) # > Hello!
history.undo(); print(doc.text) # HelloThe 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
| Approach | How undo works | Good at | Weak at |
|---|---|---|---|
| Inverse operation (above) | Each command knows how to reverse itself | Small memory per step; fast | Every command needs a correct inverse; some have none |
| Snapshot (Memento) | Save the state before executing; undo restores it | Simple and always correct | Memory: 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")));from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, asdict
from functools import partial
import json
pool = ThreadPoolExecutor(max_workers=4)
pool.submit(partial(mailer.send_invoice, "order-42")) # a callable is a command object
# For a durable queue, the command must be plain data, not a closure
@dataclass(frozen=True)
class SendInvoice:
order_id: str
queue.publish("jobs.send-invoice", json.dumps(asdict(SendInvoice("order-42"))))Requests as objects: queued, sent, replayed
- 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
| Command | Strategy | Memento | |
|---|---|---|---|
| The object represents | A request: do this, to that, with these values | A way of doing a job | A saved state of another object |
| Holds | Receiver and parameters, often undo data | Only the algorithm (and its configuration) | A snapshot, opaque to everyone but its owner |
| Who calls it, when | An invoker, possibly later, on another thread or machine | The context, right now, as part of its own work | The owner, when it restores itself |
| Can be undone, queued, logged? | Yes, that is the point | No; it has no meaning outside its context | It is the undo data |
| Example | DeleteCommand(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
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.
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.
- 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.
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?
Commands give one object per action that any trigger can run and that the history can reverse. Strategies are chosen ways of doing a job, with no notion of being stored or undone.
2. A user types A, B and C, undoes twice, then types D. What should redo do now?
A new action starts a new branch of history, so the redo stack is cleared. Re-applying B after D would apply an edit on top of a document it was never made for.
3. A DeleteCommand saves the deleted text in its constructor, before execute() runs. Later, undo puts back the wrong text. Why?
Commands can be created long before they run (queued, in a macro). Capture undo data inside execute(), when you know what is actually being removed.
4. What is the clearest difference between Command and Strategy?
DeleteCommand(doc, 5, 6) is meaningful on its own and can be stored, queued or undone. A pricing strategy only means something when a context passes it the data. Undo is common for commands but not required.
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?
Most queues deliver at least once, so handlers must be idempotent. Turning off redelivery loses commands on real failures; longer timeouts only make duplicates rarer.
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?
100 snapshots of 5 MB is 500 MB. Inverse operations or diffs store only what changed, and merging a burst of keystrokes into one command cuts the step count.
7. A "movie night" macro runs three commands; the third throws. What should MacroCommand.execute() do?
A half-applied macro leaves the system in a state no one asked for. Roll back the completed steps, last first, and report the failure; nothing is pushed onto the history.
Score 60% or more and the lesson is marked complete.