GoF pattern • Behavioral
GoFBehavioralJava example
Memento solves a specific structural problem in the design.
Capture and restore object state without exposing internals.
Pattern overview
GoF pattern
Capture and restore object state without exposing internals.
Intent
Capture an object's internal state so it can be restored later without violating encapsulation.
Problem
You need undo, rollback, or checkpoint behavior but do not want external code poking directly at internal fields.
Solution
Let the originator create opaque snapshots and restore from them when needed.
Fit and tradeoffs
FamilyGoF
CategoryBehavioral
Best used when
- For editors, configuration sessions, and stateful workflows with undo.
Tradeoffs
- Snapshots may consume memory.
- Restoration semantics can be tricky with external side effects.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
final class EditorDocument {
private String text = "";
record Snapshot(String text) {}
Snapshot save() { return new Snapshot(text); }
void restore(Snapshot snapshot) { this.text = snapshot.text(); }
void replace(String value) { this.text = value; }
}