design patterns · behavioral
Memento
Captures and externalizes an object's internal state without violating encapsulation, enabling later restoration.
Pattern
Overview
Intent
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Real-World Analogy
Ctrl+Z - the editor saves a snapshot (memento) before each change. Undo restores the last snapshot without exposing how the editor stores its text internally.
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.
Participants
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