Command Pattern for Undo/Redo
You'll learn how to implement reversible operations with command history and undo/redo stacks.
The Core Idea
The Command Pattern becomes incredibly powerful when you need to reverse actions. By storing executed commands in a command history (typically a stack), you can walk backward through operations, undoing them one by one. For redo functionality, you maintain a second stack of undone commands, allowing users to reapply actions they've reversed.
How It Works
Think of command history like a stack of index cards, each describing an action:
- Execute and Store: When a command executes, push it onto the undo stack
- Undo: Pop from the undo stack, call its
undo()method, push onto redo stack - Redo: Pop from the redo stack, call its
execute()method again, push back onto undo stack - New Command: When a fresh command executes, clear the redo stack (you can't redo after taking a new path)
Making Commands Reversible
Each command must store enough state to reverse itself. For example, a SetTemperatureCommand might save the previous temperature value in its constructor, so undo() can restore it:
class SetTemperatureCommand:
def __init__(self, thermostat, new_temp):
self.thermostat = thermostat
self.new_temp = new_temp
self.old_temp = thermostat.get_temperature() # Save for undo!
def execute(self):
self.thermostat.set_temperature(self.new_temp)
def undo(self):
self.thermostat.set_temperature(self.old_temp)
Your invoker maintains two stacks: undo_stack and redo_stack. Execute pushes to undo_stack and clears redo_stack. Undo pops from undo_stack and pushes to redo_stack.
Key Takeaway: Command Pattern enables undo/redo by storing executed commands with their reversible state in history stacks, letting you traverse backward and forward through user actions.