SyntaxPilot
Courses/Low-Level Design/Lesson 36
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 36 of 90

Command pattern

Command patterncommandconcrete commandinvokerreceiverclientencapsulating requestsundoredocommand history stackmacro commandsqueuing and logging commandsRunnable as a command

These are the notes for Low-Level Design (LLD) episode 36, the third behavioural pattern (patterns about how objects share work and talk to each other). The Command pattern turns a request into an object. Once an action is an object, you can keep it on a stack to undo and redo it, put it in a queue to run later, log it, or group many into one macro. We start with a waiter's order slip, watch Asha's notes editor fail to undo twice, and invent the pattern as the fix. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: the order slip

At a restaurant In code
The order slip: "table 4: masala chai" The command: a request turned into an object
The customer decides what to order The client: creates the command and picks its receiver
The waiter takes slips and passes them on; he doesn't cook The invoker: triggers commands without knowing what they do inside
The chef knows how to make chai The receiver: the object that does the real work

Because the order is written down, it can wait in a line, be kept for the bill, or be cancelled. That is exactly what objects give us in code: queuing, logging and undo.

2. The problem: an undo that forgets

class Editor {
    StringBuilder text = new StringBuilder();
    String previous = "";                                // remembers ONE old version
    void type(String s) { previous = text.toString(); text.append(s); }
    void undo() { text = new StringBuilder(previous); }
}
public class Main {
    public static void main(String[] args) {
        Editor e = new Editor();
        e.type("Chai");
        e.type(" with ginger");
        e.type(" and sugar");
        System.out.println("now:          " + e.text);
        e.undo();
        System.out.println("after undo 1: " + e.text);
        e.undo();
        System.out.println("after undo 2: " + e.text + "   <- expected: Chai");
    }
}
now:          Chai with ginger and sugar
after undo 1: Chai with ginger
after undo 2: Chai with ginger   <- expected: Chai

No error, just the wrong output: the second undo did nothing.

Why it failed

  • Only one old version (previous) is kept; the second change overwrote it, so "Chai" is lost.
  • The editor doesn't know what each action did, only what the text looked like before.
  • Saving a full copy of the whole text at every step would be huge for a big file.
  • Write each action down, like an order slip. Each slip knows how to do and undo itself. Keep a pile of slips, newest on top.

3. The fix: actions as objects

import java.util.*;

class Document { final StringBuilder text = new StringBuilder(); }      // the receiver
interface Command { void execute(); void undo(); }                       // the command

class TypeCommand implements Command {                                   // a concrete command
    private final Document doc; private final String s;
    TypeCommand(Document doc, String s) { this.doc = doc; this.s = s; }
    public void execute() { doc.text.append(s); }
    public void undo()    { doc.text.setLength(doc.text.length() - s.length()); }
}
class History {                                                          // the invoker
    private final Deque<Command> undos = new ArrayDeque<>(), redos = new ArrayDeque<>();
    void run(Command c) { c.execute(); undos.push(c); redos.clear(); }
    void undo() { if (!undos.isEmpty()) { Command c = undos.pop(); c.undo(); redos.push(c); } }
    void redo() { if (!redos.isEmpty()) { Command c = redos.pop(); c.execute(); undos.push(c); } }
}
public class Main {
    public static void main(String[] args) {
        Document doc = new Document(); History h = new History();        // the client wires it up
        h.run(new TypeCommand(doc, "Chai"));
        h.run(new TypeCommand(doc, " with ginger"));
        h.run(new TypeCommand(doc, " and sugar"));
        System.out.println("now:  " + doc.text);
        h.undo(); System.out.println("undo: " + doc.text);
        h.undo(); System.out.println("undo: " + doc.text);
        h.redo(); System.out.println("redo: " + doc.text);
    }
}
now:  Chai with ginger and sugar
undo: Chai with ginger
undo: Chai
redo: Chai with ginger
  • Document is the receiver: it holds the text.
  • Command is the command interface: execute() does the action, undo() reverses it.
  • TypeCommand is a concrete command: it stores which document and which text, so it can undo exactly its own change.
  • History is the invoker. It keeps two stacks (Deque used with push/pop). A stack is a pile where the last thing put on is the first taken off (LIFO: last in, first out). run executes and pushes onto the undo stack; undo pops, undoes, and pushes onto the redo stack; redo does the opposite. Together they are the command history stack.
  • Main is the client: it creates the commands and hands them to the invoker.

4. It has a name: the Command pattern

  +-----------+  creates   +--------------------+  keeps  +-------------------------+
  | Main      |----------->| TypeCommand        |-------->| «interface» Command     |
  | «client»  |            | «concrete command» | (impl.) | + execute()  + undo()   |
  +-----------+            | - doc, s           |         +-------------------------+
                           +--------------------+                   ^ keeps
                                 | acts on                          |
                           +-----------+                    +------------------+
                           | Document  |                    | History          |
                           | «receiver»|                    | «invoker»        |
                           +-----------+                    | undos, redos     |
                                                            +------------------+

The classic intent: "Encapsulate a request as an object, thereby letting you parameterize clients with different requests", queue or log requests, and support undoable operations. Encapsulating a request means packing everything needed to perform it (the action, the receiver, the arguments) into one object. Parameterize means a button or menu can be given any command object.

Role In our example Job
Client Main Creates commands, chooses receivers
Invoker History (a button, a menu, a scheduler) Runs / undoes / redoes commands; knows no details
Command Command interface execute(), undo()
Concrete command TypeCommand One action, with the data to undo it
Receiver Document Does the real work

5. The trap: a stale redo

import java.util.*;

class Document { final StringBuilder text = new StringBuilder(); }      // the receiver
interface Command { void execute(); void undo(); }                       // the command

class TypeCommand implements Command {                                   // a concrete command
    private final Document doc; private final String s;
    TypeCommand(Document doc, String s) { this.doc = doc; this.s = s; }
    public void execute() { doc.text.append(s); }
    public void undo()    { doc.text.setLength(doc.text.length() - s.length()); }
}
class History {                                                          // the invoker
    private final Deque<Command> undos = new ArrayDeque<>(), redos = new ArrayDeque<>();
    void run(Command c) { c.execute(); undos.push(c); }                  // redos NOT cleared
    void undo() { if (!undos.isEmpty()) { Command c = undos.pop(); c.undo(); redos.push(c); } }
    void redo() { if (!redos.isEmpty()) { Command c = redos.pop(); c.execute(); undos.push(c); } }
}
public class Main {
    public static void main(String[] args) {
        Document doc = new Document(); History h = new History();        // the client wires it up
        h.run(new TypeCommand(doc, "Chai"));
        h.run(new TypeCommand(doc, " with ginger"));
        h.undo(); System.out.println("undo: " + doc.text);
        h.run(new TypeCommand(doc, " with lemon"));                      // a NEW change
        System.out.println("now:  " + doc.text);
        h.redo(); System.out.println("redo: " + doc.text);
    }
}
undo: Chai
now:  Chai with lemon
redo: Chai with lemon with ginger

After an undo, Asha made a new change. The old redo stack described a future that no longer exists, but redo replayed it anyway: "with ginger" came back on top of "with lemon". The fix: a new command clears the redo stack:

import java.util.*;

class Document { final StringBuilder text = new StringBuilder(); }      // the receiver
interface Command { void execute(); void undo(); }                       // the command

class TypeCommand implements Command {                                   // a concrete command
    private final Document doc; private final String s;
    TypeCommand(Document doc, String s) { this.doc = doc; this.s = s; }
    public void execute() { doc.text.append(s); }
    public void undo()    { doc.text.setLength(doc.text.length() - s.length()); }
}
class History {                                                          // the invoker
    private final Deque<Command> undos = new ArrayDeque<>(), redos = new ArrayDeque<>();
    void run(Command c) { c.execute(); undos.push(c); redos.clear(); }   // new change: clear
    void undo() { if (!undos.isEmpty()) { Command c = undos.pop(); c.undo(); redos.push(c); } }
    void redo() { if (!redos.isEmpty()) { Command c = redos.pop(); c.execute(); undos.push(c); } }
}
public class Main {
    public static void main(String[] args) {
        Document doc = new Document(); History h = new History();        // the client wires it up
        h.run(new TypeCommand(doc, "Chai"));
        h.run(new TypeCommand(doc, " with ginger"));
        h.undo(); System.out.println("undo: " + doc.text);
        h.run(new TypeCommand(doc, " with lemon"));                      // a NEW change
        System.out.println("now:  " + doc.text);
        h.redo(); System.out.println("redo: " + doc.text);
    }
}
undo: Chai
now:  Chai with lemon
redo: Chai with lemon

6. A command must remember what it changes

Typing is easy to undo (remove the same number of characters). Deleting is not: the command must keep the deleted text, or undo has nothing to put back.

import java.util.*;

class Document { final StringBuilder text = new StringBuilder(); }
interface Command { void execute(); void undo(); }

class DeleteCommand implements Command {                 // delete the last n characters
    private final Document doc; private final int n;
    DeleteCommand(Document doc, int n) { this.doc = doc; this.n = n; }
    public void execute() { doc.text.setLength(doc.text.length() - n); }
    public void undo()    { /* put back... what? we never kept it */ }
}
public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        doc.text.append("Chai with ginger");
        Command del = new DeleteCommand(doc, 7);
        del.execute(); System.out.println("after delete: [" + doc.text + "]");
        del.undo();    System.out.println("after undo:   [" + doc.text + "]");
    }
}
after delete: [Chai with]
after undo:   [Chai with]

No error, but "ginger" is lost. Fix: execute() saves what it is about to remove, and undo() puts exactly that back.

import java.util.*;

class Document { final StringBuilder text = new StringBuilder(); }
interface Command { void execute(); void undo(); }

class DeleteCommand implements Command {                 // delete the last n characters
    private final Document doc; private final int n; private String removed = "";
    DeleteCommand(Document doc, int n) { this.doc = doc; this.n = n; }
    public void execute() {
        int end = doc.text.length();
        removed = doc.text.substring(end - n);           // remember what we remove
        doc.text.setLength(end - n);
    }
    public void undo()    { doc.text.append(removed); }  // put exactly that back
}
public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        doc.text.append("Chai with ginger");
        Command del = new DeleteCommand(doc, 7);
        del.execute(); System.out.println("after delete: [" + doc.text + "]");
        del.undo();    System.out.println("after undo:   [" + doc.text + "]");
    }
}
after delete: [Chai with]
after undo:   [Chai with ginger]

The rule for every undoable command: whatever execute() changes or throws away, it remembers first (a light command remembers whether the light was on; a money transfer remembers the amount).

7. Macro commands

A macro command is a command made of other commands. execute runs them in order; undo undoes them in reverse order (last one first), because later steps may depend on earlier ones.

import java.util.*;

class Document { final StringBuilder text = new StringBuilder(); }
interface Command { void execute(); void undo(); }
class TypeCommand implements Command {
    private final Document doc; private final String s;
    TypeCommand(Document doc, String s) { this.doc = doc; this.s = s; }
    public void execute() { doc.text.append(s); }
    public void undo()    { doc.text.setLength(doc.text.length() - s.length()); }
}
class MacroCommand implements Command {                  // many commands as ONE
    private final List<Command> steps;
    MacroCommand(List<Command> steps) { this.steps = steps; }
    public void execute() { for (Command c : steps) c.execute(); }
    public void undo() { for (int i = steps.size() - 1; i >= 0; i--) steps.get(i).undo(); }  // reverse
}
public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        doc.text.append("Order: masala dosa.");
        Command signOff = new MacroCommand(List.of(new TypeCommand(doc, " Thanks!"),
                new TypeCommand(doc, " -- Asha"), new TypeCommand(doc, " (SyntaxPilot Cafe)")));
        signOff.execute(); System.out.println(doc.text);
        signOff.undo();    System.out.println(doc.text);
    }
}
Order: masala dosa. Thanks! -- Asha (SyntaxPilot Cafe)
Order: masala dosa.

Because MacroCommand is itself a Command, the invoker treats it like any other: one undo removes all three pieces. This is the Composite idea from episode 32 (a group that looks like a single item).

8. Queuing and logging commands: Runnable as a command

Java's built-in Runnable has one method, run(), taking nothing and returning nothing: it is a command interface, so a lambda can be a command. Because commands are objects, they can be queued (a queue is a line: first in, first out) and run later, and logged (a log is a record of what was requested).

import java.util.*;

public class Main {
    static final Queue<Runnable> kitchen = new ArrayDeque<>();     // commands wait here
    static final List<String> log = new ArrayList<>();

    static void order(String name, Runnable command) {             // the waiter: just takes the slip
        log.add(name);
        kitchen.add(command);
    }
    public static void main(String[] args) throws InterruptedException {
        order("table 4: masala chai", () -> System.out.println("chef: brewing masala chai"));
        order("table 2: dosa",        () -> System.out.println("chef: making dosa"));
        order("table 4: samosa",      () -> System.out.println("chef: frying samosa"));
        System.out.println("orders taken: " + log.size() + ", nothing cooked yet");

        Thread chef = new Thread(() -> {                           // a Thread runs a Runnable
            while (!kitchen.isEmpty()) kitchen.poll().run();       // executed LATER, in order
        });
        chef.start(); chef.join();
        System.out.println("log: " + log);
    }
}
orders taken: 3, nothing cooked yet
chef: brewing masala chai
chef: making dosa
chef: frying samosa
log: [table 4: masala chai, table 2: dosa, table 4: samosa]

A thread is a separate worker that runs code at the same time as the rest of the program. new Thread(runnable) takes a command; start() begins it and join() waits until it finishes. Real systems use the same idea: ExecutorService thread pools take Runnable tasks, job queues store commands to run on other machines, and a database can replay a log of commands after a crash.

9. When Command helps (and when it doesn't)

Use it when Skip it when
You need undo/redo (editors, drawing apps, form wizards) Nothing is ever undone, queued or logged: just call the method
Work must run later or in order (job queues, schedulers)
You need a record of requests (audit trail, replay after a crash)
A button, a menu item and a shortcut must trigger the same action

Command vs Strategy (episode 34): both put behaviour in an object. A strategy is a way of doing one job (how to pay) that the context picks. A command is a whole request (what to do, on which receiver, with which data) that can run now, later, or in reverse.

Common mistakes

Mistake What you see Why Fix
One previous field for undo No error: after undo 2: Chai with ginger Only one old version kept A stack of commands
Redo stack not cleared on a new command No error: redo: Chai with lemon with ginger Redo replays a future that no longer exists redos.clear() in run()
Undo without saved state No error: after undo: [Chai with] The command didn't remember what it changed Store it in execute()
Macro undo in the same order Wrong state in between Later steps depend on earlier ones Undo in reverse
Unlimited history Memory grows forever in long sessions Every command is kept Cap the stack (see practice 2)
Command calls the invoker back Confusing loops Roles mixed up Commands talk only to their receiver

Mini project: a smart-home "Good night" button

One macro: hall light off, bedroom fan to speed 1. Undo restores what each device had before.

Solution
import java.util.*;

class Light { boolean on = true;  void set(boolean v) { on = v; System.out.println("light " + (v ? "ON" : "OFF")); } }
class Fan   { int speed = 3;      void set(int s)     { speed = s; System.out.println("fan speed " + s); } }

interface Command { void execute(); void undo(); }
class LightCommand implements Command {
    private final Light light; private final boolean target; private boolean before;
    LightCommand(Light l, boolean target) { light = l; this.target = target; }
    public void execute() { before = light.on; light.set(target); }        // remember the old state
    public void undo()    { light.set(before); }
}
class FanCommand implements Command {
    private final Fan fan; private final int target; private int before;
    FanCommand(Fan f, int target) { fan = f; this.target = target; }
    public void execute() { before = fan.speed; fan.set(target); }
    public void undo()    { fan.set(before); }
}
class MacroCommand implements Command {
    private final List<Command> steps;
    MacroCommand(List<Command> steps) { this.steps = steps; }
    public void execute() { steps.forEach(Command::execute); }
    public void undo() { for (int i = steps.size() - 1; i >= 0; i--) steps.get(i).undo(); }
}
public class Main {
    public static void main(String[] args) {
        Light hall = new Light(); Fan bedroom = new Fan();
        Command goodNight = new MacroCommand(List.of(new LightCommand(hall, false), new FanCommand(bedroom, 1)));
        System.out.println("-- good night --"); goodNight.execute();
        System.out.println("-- oops, undo --"); goodNight.undo();
    }
}
-- good night --
light OFF
fan speed 1
-- oops, undo --
fan speed 3
light ON

Each command stores the device's old state in execute(), so undo() restores exactly that, and the macro undoes in reverse.

Practice

1. Write a ReplaceCommand(doc, oldWord, newWord) that replaces the last occurrence of a word and can be undone. What must it remember?

Answer

The position where it replaced, and both words. execute() finds int at = doc.text.lastIndexOf(oldWord), stores at, and calls doc.text.replace(at, at + oldWord.length(), newWord); undo() calls doc.text.replace(at, at + newWord.length(), oldWord). If at is -1 (word not found), execute() should do nothing and undo() too.

2. Limit History to the last 50 commands.

Answer
import java.util.*;

class Document { final StringBuilder text = new StringBuilder(); }
interface Command { void execute(); void undo(); }
class TypeCommand implements Command {
    private final Document doc; private final String s;
    TypeCommand(Document doc, String s) { this.doc = doc; this.s = s; }
    public void execute() { doc.text.append(s); }
    public void undo()    { doc.text.setLength(doc.text.length() - s.length()); }
}
class History {
    private static final int LIMIT = 50;
    private final Deque<Command> undos = new ArrayDeque<>(), redos = new ArrayDeque<>();
    void run(Command c) {
        c.execute(); undos.push(c); redos.clear();
        if (undos.size() > LIMIT) undos.removeLast();       // forget the OLDEST command
    }
    void undo() { if (!undos.isEmpty()) { Command c = undos.pop(); c.undo(); redos.push(c); } }
    int size() { return undos.size(); }
}
public class Main {
    public static void main(String[] args) {
        Document doc = new Document(); History h = new History();
        for (int i = 0; i < 60; i++) h.run(new TypeCommand(doc, "x"));
        System.out.println("typed: " + doc.text.length() + ", undo steps kept: " + h.size());
        for (int i = 0; i < 100; i++) h.undo();
        System.out.println("after 100 undos: " + doc.text.length() + " characters left");
    }
}
typed: 60, undo steps kept: 50
after 100 undos: 10 characters left

push adds at the front of the Deque, so the oldest command is at the end: removeLast() forgets it. After 50 undos, the first 10 changes can no longer be undone.

3. A "Save" button, the File menu's Save item and Ctrl+S should all do the same thing. How does Command help?

Answer

Create one SaveCommand and give the same object to all three invokers. The save logic lives in one place, and you can disable all three at once by disabling the command.

Quick quiz

h.run(new TypeCommand(doc, "A"));
h.run(new TypeCommand(doc, "B"));
h.run(new TypeCommand(doc, "C"));
h.undo();
h.undo();
h.redo();
System.out.println(doc.text);

(a) A (b) AB (c) ABC (d) AC

Answer

(b) AB. The two undos remove C, then B, leaving A. Redo takes the newest command from the redo stack, B, and runs it again.

Interview questions

  1. What is the Command pattern? A behavioural pattern that encapsulates a request as an object, so it can be passed around, queued, logged and undone.
  2. Participants? Client, invoker, command interface, concrete command, receiver.
  3. How do you implement undo/redo? Each command implements undo(); the invoker keeps an undo stack and a redo stack; a new command clears the redo stack.
  4. What must a command store to be undoable? Everything needed to reverse it: the receiver, the arguments, and any state it overwrote or removed.
  5. What is a macro command? A command made of commands; executes in order, undoes in reverse.
  6. Command in the JDK? Runnable and Callable tasks given to Thread and ExecutorService; Swing's Action.
  7. Command vs Strategy? Strategy varies how one job is done; Command represents what request to perform, often for later.
  8. Command vs Memento? Command undoes by running a reverse action; Memento undoes by restoring a saved snapshot of state. They are often combined.
  9. Downsides? Many small classes (lambdas help for simple, non-undoable commands); memory for long histories.
  10. Where is it used? Editors, transactional systems, job/task queues, remote controls, game input replay, database write-ahead logs.

Glossary

Term Meaning, with an example
Behavioural pattern A pattern about how objects share work and communicate
Command pattern Turn a request into an object. new TypeCommand(doc, "Chai")
Command The interface for a request: execute() and undo()
Concrete command One kind of action, with what it needs to undo itself. TypeCommand
Invoker Triggers commands without knowing their details. History, a button
Receiver Does the real work. Document
Client Creates commands and sets their receivers. Main
Encapsulating requests Packing an action, its receiver and its data into one object
Parameterize Give an invoker any command object, so the same button can do different things
Undo / redo Reverse the last action / perform an undone action again
Stack A pile: last in, first out. Deque.push / pop
Undo stack / redo stack The commands that can be undone / redone
Command history stack The undo and redo stacks together
Deque / ArrayDeque A double-ended queue; used here as a stack
Macro command A command made of commands; undo in reverse
Queue A line: first in, first out. Queue<Runnable>
Queuing commands Storing commands to run later, in order
Logging commands Keeping a record of every request, for audit or replay
Runnable Java's built-in command interface: void run()
Lambda A short way to write a one-method interface. () -> System.out.println("chef: making dosa")
Thread A separate worker running code at the same time as the rest of the program
start() / join() Begin a thread / wait for it to finish
StringBuilder A changeable string. append, setLength
Composite A group that looks like one item (episode 32)
Strategy One algorithm per class, swappable (episode 34)
Memento A pattern that undoes by restoring a saved snapshot of an object's state (episode 42)

Summary

  • An undo that keeps one old version can't go back two steps.
  • Command turns each request into an object with execute() and undo(): client creates it, invoker runs it, receiver does the work.
  • An undo stack and a redo stack give unlimited undo/redo; a new command clears the redo stack.
  • Macro commands run in order and undo in reverse.
  • Because commands are objects, they can be queued, logged and run later: Runnable is Java's built-in command.

Next episode: The State pattern: when an object's behaviour depends on the state it's in.