The Command pattern is a behavioral pattern that encapsulates a request as a standalone object, so the action, its parameters, and its receiver are all bundled together and can be passed around, queued, logged, or undone like any other object.
A text editor's undo stack works by storing executed Command objects; each command knows both how to redo its action and how to reverse it, so pressing undo just calls the last command's undo() method.
import java.util.ArrayDeque;
import java.util.Deque;
public class CommandUndoDemo {
interface Command { void execute(); void undo(); }
static class Editor { StringBuilder text = new StringBuilder(); }
static class TypeCommand implements Command {
private final Editor editor;
private final String words;
TypeCommand(Editor editor, String words) { this.editor = editor; this.words = words; }
public void execute() { editor.text.append(words); }
public void undo() { editor.text.setLength(editor.text.length() - words.length()); }
}
// The invoker stores commands; it doesn't know what they do
static class History {
private final Deque<Command> done = new ArrayDeque<>();
void run(Command c) { c.execute(); done.push(c); }
void undo() { if (!done.isEmpty()) done.pop().undo(); }
}
public static void main(String[] args) {
Editor editor = new Editor();
History history = new History();
history.run(new TypeCommand(editor, "Hello"));
history.run(new TypeCommand(editor, " World"));
System.out.println(editor.text);
history.undo();
System.out.println(editor.text);
}
}Hello World
Hello
A concise interview answer is
Command encapsulates a request as an object with an execute() method, bundling the action and its receiver together, which decouples the sender from the actual execution logic and makes it easy to queue, log, or undo operations since each request is just an object you can store and pass around.
Last updated: 1 November 2026
Previous question: Provide an example where the Strategy pattern simplifies the management of multiple algorithms.
Next question: How would you implement the Command pattern in Java?