Memento
Intent
Saves and restores an object's previous state without revealing its implementation.
Problem
An editor needs undo, but snapshotting requires access to private fields.
Solution
The originator produces snapshot objects itself; a caretaker stores them.
Real-world analogy
Think of it like this
Saving your game before the boss fight, so you can reload if things go wrong.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Originator — Originator produces snapshots of its own state and restores from them.
- 2Memento — Memento is an immutable snapshot of the originator's state.
- 3Caretaker — Caretaker knows when to capture and restore, and keeps a history stack.
Code example
A C++ code sample for Memento is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.
Applicability
Use Memento when undo / snapshots.
Use Memento when direct access to fields would break encapsulation.
Pros and cons
Pros
- Snapshots without breaking encapsulation
Cons
- Memory use with frequent snapshots
Check yourself
Check yourself
A form editor must restore its previous state when the user presses Cancel.
Saved in this browser only. Part of Behavioral patterns (0/11).