LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 37 OF 48

Command Pattern in Java: Undo, Redo, Queues and Request Logs

The Command pattern with a playlist editor: turning a request into an object, the invoker, receiver and command roles, undo and redo with two stacks, why a new edit clears redo, macro commands, queuing and logging commands, how Command differs from Strategy and Memento, where Java uses it, and where it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 202 lines, with a small main() demo. Save it as PlaylistUndoDemo.java, then run javac PlaylistUndoDemo.java && java PlaylistUndoDemo.

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/** Command pattern: playlist edits as objects, with undo, redo, macros and a log. */
public class PlaylistUndoDemo {

    // ---------- 1. The problem: buttons edit directly, undo has to guess ----------
    static final class NaiveScreen {
        final List<String> songs = new ArrayList<>(List.of("Intro", "Rain Song", "Night Drive"));
        String lastAction = "";

        void onRemoveTapped(int index) {
            songs.remove(index);
            lastAction = "remove"; // but which song, and where? undo cannot know
        }
    }

    // ---------- 2. The receiver: does the real work, knows nothing about undo ----------
    static final class Playlist {
        private final List<String> songs = new ArrayList<>();

        void insertAt(int index, String song) { songs.add(index, song); }

        String removeAt(int index) { return songs.remove(index); }

        int size() { return songs.size(); }

        @Override
        public String toString() { return songs.toString(); }
    }

    // ---------- 3. The command interface and concrete commands ----------
    interface PlaylistEdit {
        void apply();

        void undo();

        String describe();
    }

    static final class AddSong implements PlaylistEdit {
        private final Playlist playlist;
        private final String song;
        private int index = -1; // captured when applied

        AddSong(Playlist playlist, String song) {
            this.playlist = playlist;
            this.song = song;
        }

        @Override
        public void apply() {
            index = playlist.size();
            playlist.insertAt(index, song);
        }

        @Override
        public void undo() { playlist.removeAt(index); }

        @Override
        public String describe() { return "add " + song; }
    }

    static final class RemoveSong implements PlaylistEdit {
        private final Playlist playlist;
        private final int index;
        private String removed; // remembered so undo can put it back

        RemoveSong(Playlist playlist, int index) {
            this.playlist = playlist;
            this.index = index;
        }

        @Override
        public void apply() { removed = playlist.removeAt(index); }

        @Override
        public void undo() { playlist.insertAt(index, removed); }

        @Override
        public String describe() {
            return "remove #" + index + (removed == null ? "" : " (" + removed + ")");
        }
    }

    static final class MoveSong implements PlaylistEdit {
        private final Playlist playlist;
        private final int from;
        private final int to;

        MoveSong(Playlist playlist, int from, int to) {
            this.playlist = playlist;
            this.from = from;
            this.to = to;
        }

        @Override
        public void apply() { playlist.insertAt(to, playlist.removeAt(from)); }

        @Override
        public void undo() { playlist.insertAt(from, playlist.removeAt(to)); }

        @Override
        public String describe() { return "move #" + from + " to #" + to; }
    }

    /** A macro is itself a command: apply in order, undo in reverse. */
    record MacroEdit(String name, List<PlaylistEdit> steps) implements PlaylistEdit {
        @Override
        public void apply() { steps.forEach(PlaylistEdit::apply); }

        @Override
        public void undo() {
            for (int i = steps.size() - 1; i >= 0; i--) {
                steps.get(i).undo();
            }
        }

        @Override
        public String describe() { return name + " (" + steps.size() + " steps)"; }
    }

    // ---------- 4. The invoker: runs, remembers, undoes, redoes ----------
    static final class EditHistory {
        private static final int LIMIT = 100;
        private final Deque<PlaylistEdit> done = new ArrayDeque<>();
        private final Deque<PlaylistEdit> undone = new ArrayDeque<>();
        private final List<String> log = new ArrayList<>();

        void run(PlaylistEdit edit) {
            edit.apply();
            done.push(edit);
            undone.clear(); // a new edit starts a new branch: the old redo future is gone
            if (done.size() > LIMIT) {
                done.removeLast(); // forget the oldest edit
            }
            log.add("run  " + edit.describe());
        }

        boolean undo() {
            PlaylistEdit edit = done.poll();
            if (edit == null) {
                return false;
            }
            edit.undo();
            undone.push(edit);
            log.add("undo " + edit.describe());
            return true;
        }

        boolean redo() {
            PlaylistEdit edit = undone.poll();
            if (edit == null) {
                return false;
            }
            edit.apply();
            done.push(edit);
            log.add("redo " + edit.describe());
            return true;
        }

        List<String> log() { return log; }
    }

    public static void main(String[] args) {
        NaiveScreen naive = new NaiveScreen();
        naive.onRemoveTapped(1);
        System.out.println("Naive: " + naive.songs + ", last action '" + naive.lastAction + "', song lost");

        Playlist playlist = new Playlist();
        EditHistory history = new EditHistory();

        history.run(new MacroEdit("add starter pack", List.of(
                new AddSong(playlist, "Intro"),
                new AddSong(playlist, "Rain Song"),
                new AddSong(playlist, "Night Drive"))));
        System.out.println("after macro:   " + playlist);

        history.run(new RemoveSong(playlist, 1));
        System.out.println("after remove:  " + playlist);

        history.undo();
        System.out.println("after undo:    " + playlist);

        history.redo();
        System.out.println("after redo:    " + playlist);

        history.undo();
        history.run(new MoveSong(playlist, 2, 0)); // new edit clears redo
        System.out.println("after move:    " + playlist);
        System.out.println("redo possible? " + history.redo());

        history.undo();
        history.undo(); // undoes the whole macro in one step
        System.out.println("after 2 undos: " + playlist);

        System.out.println("log:");
        history.log().forEach(line -> System.out.println("  " + line));
    }
}

Notes

The problem

Here is the naive version. Each button handler changes the playlist directly. To support undo, we store a string saying what the last action was. But undo also needs the details: which song was removed, from which position. So the screen collects more and more fields, a switch grows for every kind of edit, and we only ever get one level of undo. Logging every edit or replaying them later is just as messy.

The naive version
void onRemoveTapped(int i) {
    playlist.remove(i);
    lastAction = "remove";  // and the song?
}
void onUndoTapped() {
    switch (lastAction) {
        case "remove" -> ???
        case "move" -> ???
    }
}  // one level of undo, at best

The idea

The idea in one sentence: wrap a request in an object that knows how to carry it out. The object holds the target and the arguments, and, for undo, whatever it needs to reverse the action. The code that triggers a command does not need to know what it does. It only calls apply. And because the request is now an object, it can be stored, queued, logged, sent to another thread or combined with others.

In one sentence
  • wrap a request in an object
  • that knows how to carry it out
  • the object can then be:
  • stored for undo and redo
  • put in a queue for later
  • written to a log
  • sent to another thread
  • combined into a macro

The structure

The participants. PlaylistScreen is the client: it creates a command when the user taps a button. EditHistory is the invoker: it runs commands and remembers them for undo and redo. PlaylistEdit is the command interface, with apply and undo. AddSong, RemoveSong and MoveSong are concrete commands. Playlist is the receiver, the object that actually does the work. The invoker never touches the playlist directly.

The code: a command

The command interface has apply, undo and describe. Look at RemoveSong. It is created with the playlist and a position. When it is applied, it removes the song and keeps it in a field. Undo puts that exact song back at the same position. This is the heart of undo with commands: each command saves just enough information, at the moment it runs, to reverse itself exactly.

RemoveSong
interface PlaylistEdit {
    void apply(); void undo();
    String describe(); }

final class RemoveSong implements ...
    private String removed;  // for undo
    public void apply() {
      removed = playlist.removeAt(index); }
    public void undo() {
      playlist.insertAt(index, removed); }

The code: invoker

The invoker keeps two stacks. Run applies a command and pushes it onto the done stack. Undo pops the latest command, calls its undo, and pushes it onto the undone stack. Redo does the opposite. One rule is easy to forget: running a brand new command clears the redo stack. After you undo and then make a different edit, the old future no longer makes sense, so it must be thrown away.

EditHistory
Deque<PlaylistEdit> done =
    new ArrayDeque<>();  // undo stack
Deque<PlaylistEdit> undone =
    new ArrayDeque<>();  // redo stack
void run(PlaylistEdit e) {
    e.apply(); done.push(e);
    undone.clear(); }  // new branch
void undo() { var e = done.pop();
    e.undo(); undone.push(e); }
void redo() { var e = undone.pop();
    e.apply(); done.push(e); }

Run-through

Let us run it. The user taps remove on the second song. The screen builds a RemoveSong command for position one and hands it to the history. The history applies it, and the command removes the song from the playlist and remembers it. Then the user taps undo. The history pops that command and calls undo, and the command inserts the same song back at position one. The screen never wrote any undo logic.

Undo done right

A few rules make undo reliable. Capture what you need when the command is applied, not when it is created, because the playlist may have changed in between. Undo strictly in reverse order. Store values, not references to objects that might change later. Cap the history, for example at one hundred edits, and drop the oldest, or memory grows forever. And be honest: some actions, like sending an email, cannot be undone. Mark them, or undo them with a compensating action.

Rules for undo
  • capture state when applied,
  • not when created
  • undo in reverse order
  • store values, not references
  • to objects that may change
  • cap the history (say 100)
  • and drop the oldest
  • some actions cannot be undone
  • (sending an email): say so
  • or compensate

Macro commands

Commands combine nicely. A macro command holds a list of other commands. Applying it applies each step in order, and undoing it undoes each step in reverse order. To the history it is just one command, so one tap of undo reverses a whole action, like add these three songs to the top. This is also how you build a recorded sequence that the user can replay.

MacroEdit
record MacroEdit(String name,
        List<PlaylistEdit> steps)
        implements PlaylistEdit {
    public void apply() {
      steps.forEach(PlaylistEdit::apply); }
    public void undo() {
        for (int i = steps.size() - 1;
                i >= 0; i--)
            steps.get(i).undo(); }
}

Queue it, log it

Undo is only one use. Because a command is an object, it can sit in a queue until a worker thread picks it up, or wait until a scheduled time. A failed command can simply be run again. Each command can be written to an append only log, and replaying that log rebuilds the state after a crash, which is how many databases and event sourced systems work. A mobile app can queue edits while offline and send them when the network comes back.

Beyond undo
  • queue: a worker takes commands
  • off a queue and runs them
  • schedule: run at a later time
  • retry: run the same object
  • again after a failure
  • log: write each command to an
  • append-only log; replay it
  • to rebuild state after a crash
  • offline: queue edits, sync
  • them when back online

When to use it

Use Command when a request needs a life of its own: undo and redo, queues, scheduled jobs, retries, audit logs and replay, or when a button, a menu item and a keyboard shortcut should all trigger the same action. Skip it when you simply call a method and nothing is stored, delayed or reversed. Then a command class per action is extra ceremony that hides a one line call.

Use it / skip it
  • use it for:
  • undo and redo
  • queues, schedules, retries
  • audit logs and replay
  • buttons and menus that share
  • one action
  • skip it when:
  • the call is direct and final
  • nothing is stored or undone

Command vs neighbours

How does Command differ from its neighbours? A strategy is a way of doing a job, like a shuffle rule, plugged into an object and used again and again. A command is one specific request, with its target and arguments, ready to run, store or undo. Memento also supports undo, but by saving a snapshot of the whole state. Command undo reverses each step instead, which is usually much smaller. The two are often combined when reversing a step is hard.

Do not mix them up
  • Strategy: one way of doing a
  • job, chosen and plugged in
  • (a ShuffleRule)
  • Command: one specific request,
  • with its target and args,
  • ready to run, store or undo
  • Memento: undo by saving a
  • snapshot of the whole state
  • Command undo: reverse each
  • step, usually much smaller

In Java

Java uses the idea everywhere. A Runnable or a Callable handed to an executor service is a command: a request wrapped in an object and queued for another thread. Swing has an Action interface, so one action object can back a button, a menu item and a keyboard shortcut. Swing's undo package has UndoableEdit, with undo and redo methods, and an UndoManager that keeps the history, which is the same design we just built.

Where you have seen it
  • Runnable and Callable given
  • to an ExecutorService:
  • requests queued for threads
  • Swing Action: one action for
  • a button, menu and shortcut
  • javax.swing.undo:
  • UndoableEdit, UndoManager
  • job and message queues in
  • frameworks

In LLD interviews

In machine coding rounds, listen for undo, redo, queue, schedule, retry or audit. A text editor or drawing board is the classic undo and redo problem. In a chess game, each move is a command, so taking back a move is just undo. An elevator system can queue floor requests as command objects for the scheduler. A task scheduler runs jobs as commands. A banking design logs every transaction and reverses one with a compensating command.

Where it fits
  • text editor: undo and redo
  • drawing board or whiteboard
  • chess or board games: take
  • back a move
  • elevator: floor requests
  • queued for the scheduler
  • task scheduler: jobs as
  • commands
  • bank: transactions with an
  • audit log and reversal

Mistakes to avoid

Common mistakes. An undo that is not the exact inverse, such as removing by name when the playlist holds the same song twice. Forgetting to clear the redo stack after a new edit. Letting the history grow forever. A command that holds a reference to the whole screen instead of just the playlist and its arguments. And putting real logic in the invoker. The invoker should only run and remember. The command and the receiver do the work.

Common mistakes
  • undo that is not the exact
  • inverse of apply
  • forgetting to clear redo
  • after a new edit
  • unbounded history
  • command holds the screen,
  • not just what it needs
  • logic in the invoker instead
  • of the command or receiver

Interview questions

What is the Command pattern?

It wraps a request, its target and its arguments in an object with a method such as execute or apply. The code that triggers it does not need to know what it does, and the request can be stored, queued, logged, retried or undone.

What are the invoker, the receiver and the client?

The client creates the command and sets its receiver. The invoker runs commands and may keep them in a history or queue. The receiver is the object that does the real work, such as the playlist or the document.

How do you implement undo and redo with commands?

Keep two stacks. Running a command applies it and pushes it on the undo stack; undo pops it, calls its undo method and pushes it on the redo stack; redo does the reverse. A new command clears the redo stack because the undone future is no longer valid.

What should a command store to support undo?

Just enough to reverse itself exactly, captured when it is applied: the position and value it removed, or the old value it replaced. Store values rather than references to objects that may change later.

How is Command different from Strategy?

A strategy is an interchangeable algorithm plugged into an object and reused. A command is one specific request with its target and arguments, often created per action, which can be stored, queued or undone.

How do Command and Memento compare for undo?

Command undoes by reversing each step, which needs little memory but requires an exact inverse. Memento undoes by restoring a saved snapshot of the state, which is simpler to get right but can use much more memory; they are often combined.

Where does Java use the Command pattern?

Runnable and Callable submitted to an ExecutorService are commands queued for worker threads. Swing’s Action lets a button, menu item and shortcut share one action, and javax.swing.undo provides UndoableEdit and UndoManager for undo history.

How would you add an audit log or crash recovery with commands?

Write each command, as data, to an append-only log before or after applying it. To recover, start from a known state and replay the log in order. This is the same idea behind write-ahead logs and event sourcing.