In what situations would you use the Command pattern, such as in undo/redo operations?

The Command pattern fits any situation where an action needs to be represented as a first-class object that can be stored, passed around, queued, or reversed, rather than executed immediately and forgotten. Undo/redo is the most common example, but it's far from the only one.

Key Points

Example

A text editor can push each edit as a Command onto an undo stack; calling undo() pops the last command and calls its reverse() method to restore the previous text state.

import java.util.ArrayDeque;
import java.util.Deque;

public class UndoRedoCommands {

    interface Command { void execute(); void reverse(); }

    static class Document { String text = ""; }

    static class ReplaceTextCommand implements Command {
        private final Document doc;
        private final String newText;
        private String oldText;
        ReplaceTextCommand(Document doc, String newText) { this.doc = doc; this.newText = newText; }
        public void execute() { oldText = doc.text; doc.text = newText; }
        public void reverse() { doc.text = oldText; }
    }

    static final Deque<Command> undoStack = new ArrayDeque<>();
    static final Deque<Command> redoStack = new ArrayDeque<>();

    static void perform(Command c) { c.execute(); undoStack.push(c); redoStack.clear(); }
    static void undo() { Command c = undoStack.pop(); c.reverse(); redoStack.push(c); }
    static void redo() { Command c = redoStack.pop(); c.execute(); undoStack.push(c); }

    public static void main(String[] args) {
        Document doc = new Document();
        perform(new ReplaceTextCommand(doc, "Draft 1"));
        perform(new ReplaceTextCommand(doc, "Draft 2"));
        System.out.println("Now: " + doc.text);

        undo();
        System.out.println("After undo: " + doc.text);
        redo();
        System.out.println("After redo: " + doc.text);
    }
}

Output

Now: Draft 2

After undo: Draft 1

After redo: Draft 2

Interview Tip

A concise interview answer is

I'd reach for Command whenever an action needs to exist as an object rather than just happen immediately — undo/redo is the classic case, where each command stores enough state to reverse itself. It's equally useful for task queues, scheduling, and logging, anywhere you need to decouple 'what to do' from 'when and how many times to do it.'

Last updated: 1 November 2026

Previous question: How would you implement the Command pattern in Java?

Next question: What are the advantages of using the Command pattern in event-driven systems?

More Java Design Patterns interview questions

All Java Design Patterns questions