design patterns ·
Memento
Captures and externalizes an object's internal state without violating encapsulation, enabling later restoration.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
When you need undo/redo, you need to save the object's state at each point. But if you expose internal state for saving, you break encapsulation. Memento lets the Originator save/restore its own state via an opaque snapshot object.
Originator creates a Memento containing its state snapshot. Caretaker stores mementos (e.g., in a stack) without inspecting them. When undo is triggered, Caretaker gives the memento back to Originator which restores state from it.
When to use
Undo/redo in text editors and drawing apps, game save states, transaction rollback, snapshot/restore functionality.
When not to
When state changes are frequent and lightweight - undo may be cheaper via Command+inverse. When the full state is too large to snapshot.
Key insights
- The Memento object is opaque to the Caretaker - it only stores and retrieves it
- Only the Originator knows how to interpret/restore state from a Memento
- A history stack of Mementos enables unlimited undo steps
- Game save states are Mementos - the game engine (Originator) creates and restores them