Memento
Intermediate · 12 min read · Low-Level Design, Behavioral Patterns
Snapshots for undo without breaking encapsulation.
The idea in plain words
A Memento is a saved snapshot of an object's state, so you can put the object back the way it was later. The object makes the snapshot itself, so nobody else has to poke at its private fields.
The problem
You want undo in an editor, "revert to last saved" in a form, rollback of a game to a checkpoint, or restoring an object after a failed multi-step operation. To restore state you must save it somewhere. But:
The solution
Let the object create its own snapshot (the memento) and restore itself from one. Other objects (the caretaker) store mementos but can't look inside them.
Design concerns
Memento + Command for undo
Command and Memento combine naturally: before a command executes, it asks the receiver for a memento; undo() restores it. This avoids writing an inverse operation for every command — at the cost of memory.
Where you've seen it
Pros and cons
Related patterns
Undo and redo together
Real editors need both directions. The caretaker keeps two stacks: an undo stack of states to go back to, and a redo stack of states you undid. Two rules make it correct:
Persistent mementos: save games and drafts
When mementos are written to disk or sent over the network, new concerns appear:
Interview questions
- How does Memento preserve encapsulation?
- Memento or inverse operations for undo — how do you choose?
- Why does making a new edit clear the redo stack?
Further reading
Key takeaways
- Memento lets an object save and restore its own state without exposing it.
- Originator creates/restores; memento is immutable and opaque; caretaker only stores.
- Bound history and consider diffs to control memory.
- Combine with Command for undo/redo.
- Undo plus redo needs two stacks; a new edit clears redo. Persisted mementos need versioning and validation.