Implementing Undo with Memento and Command
What You'll Learn
You'll learn how to combine the Memento and Command patterns to create a powerful undo/redo system for your applications.
The Power of Combining Patterns
While the Command pattern lets you encapsulate actions as objects and the Memento pattern captures object state, combining them creates robust undo functionality that's both flexible and safe.
Here's how they work together:
The Command-Memento Marriage
Think of Command as recording what action happened (like "delete paragraph 3") and Memento as recording the state before it happened (like "paragraph 3 contained this text"). Together, they give you everything needed to reverse an action.
Implementation Strategy
Each Command object holds two responsibilities:
- Execute the operation (already familiar from Command pattern)
- Store a Memento before executing, capturing the receiver's state
When undoing:
- The command retrieves its stored Memento
- It restores the receiver to that previous state
- The action is effectively reversed
Why This Combination Works
Command provides the framework for storing and managing executable operations in a history list. Memento provides encapsulated state snapshots without exposing internal object details. Neither pattern alone gives you both action replay and state restoration.
For example, a text editor might use:
InsertTextCommandstores a Memento of cursor position and document state- When undone, the Memento restores the exact pre-insertion state
- The command history stack tracks multiple commands for multi-level undo
This approach scales beautifully—you can undo/redo through dozens of operations by traversing your command history, each command carrying its own state snapshot.
Key Takeaway: Combining Command with Memento creates professional-grade undo/redo systems where Commands track what changed and Mementos preserve how to reverse it, giving you complete operation history without exposing object internals.