How does the Command pattern facilitate undo/redo functionality?
The Command pattern is ideal for implementing undo/redo, because each action is stored as an object that knows what was done and how to undo it.
1. A Command Encapsulates an Operation and Its Reverse Action
Each command object implements two methods:
execute()- performs the action,undo()- reverses it (restores the previous state).
Each command knows what to change and how to revert it.
2. Storing Command History
After execution, the command is added to a history stack:
java
Stack<Command> history = new Stack<>();
command.execute();
history.push(command);When the last action needs to be undone:
java
if (!history.isEmpty()) history.pop().undo();For redo, removed commands can be kept in a separate stack and re-executed by calling execute().
3. Example (Java)
java
interface Command {
void execute();
void undo();
}
class TextEditor {
private StringBuilder text = new StringBuilder();
void write(String s) { text.append(s); }
void delete(int count) { text.delete(text.length() - count, text.length()); }
String getText() { return text.toString(); }
}
class WriteCommand implements Command {
private TextEditor editor;
private String text;
public WriteCommand(TextEditor editor, String text) {
this.editor = editor;
this.text = text;
}
public void execute() { editor.write(text); }
public void undo() { editor.delete(text.length()); }
}Usage:
java
TextEditor editor = new TextEditor();
Command cmd = new WriteCommand(editor, "Hello");
cmd.execute();
cmd.undo();4. How It Works
- Each command stores the data needed to undo it.
- After execution, the command is recorded in the history.
- Calling
undo()invokes the command'sundo()method. - Calling
redo()callsexecute()again.
5. Advantages
- No need to write separate rollback logic - it's built into the command.
- You can implement multi-level undo/redo via a stack.
- The client code doesn't know how the action is actually performed or undone.
Summary:
The Command pattern makes undo/redo possible,
because each operation exists as an object with its own history,
capable of executing and undoing itself,
creating a flexible and manageable system of actions.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.