Undo and Redo with Command Pattern
What you'll learn: How storing executed commands enables powerful undo/redo functionality in your applications.
The Core Idea
Once you've encapsulated operations as command objects (from the previous lesson), you can store them in a history stack. Each executed command gets pushed onto this stack. When the user wants to undo, you pop the most recent command and call its undo() method. For redo, you maintain a separate stack of undone commands and re-execute them when needed.
Analogy: Think of a text editor's undo feature. Every action you take (typing, deleting, formatting) is like a command card placed on a stack. Hitting "undo" picks up the top card and reverses what it says. The card then moves to a "redo pile" in case you change your mind.
How It Works
When a command executes successfully:
- Store the command object in an "undo stack"
- Clear any existing "redo stack" (new actions invalidate future redos)
For undo:
- Pop the most recent command from the undo stack
- Call its
undo()method to reverse the operation - Push this command onto the redo stack
For redo:
- Pop a command from the redo stack
- Call its
execute()method again - Push it back onto the undo stack
Why This Matters
This pattern requires that commands store enough state to reverse themselves. For example, a "DeleteText" command must remember what was deleted and where, so it can restore it during undo.
Key Takeaway: By maintaining history stacks of command objects with reversible operations, you transform simple actions into a full undo/redo system—all because commands are first-class, storable objects.