3.6 Memento
The Memento pattern captures an object's internal state and stores it externally without breaking encapsulation, so the object can later be restored to that state. In one line: it is the object-oriented expression of "undo" and "save."
In the lab below, adjust a state value and "save a snapshot" anytime, then click any snapshot on the timeline to restore — the snapshot's internals are opaque to you.
Loading interactive lab...
Three roles, each with a job
java
class Editor { // Originator: owns the state
private String content;
Memento save() { return new Memento(content); } // create snapshot
void restore(Memento m) { content = m.getState(); } // restore
static class Memento { // Memento: opaque state container
private final String state;
private Memento(String state) { this.state = state; }
private String getState() { return state; }
}
}
class History { // Caretaker: keeps, never peeks
private Deque<Editor.Memento> stack = new ArrayDeque<>();
}- Originator: owns the state and creates/restores mementos.
- Memento: the state-holding object, exposing its internals only to the Originator.
- Caretaker: keeps mementos (e.g., an undo stack) but never reads or modifies their contents.
This "the caretaker keeps but doesn't peek" design is the key to not breaking encapsulation. The editor lab below lets you type, save, and restore to any version.
Loading interactive lab...
Loading concept check...
Loading concept check...
Cost and reality
- Memory: saving full snapshots frequently is memory-hungry. Common optimizations store only deltas (diffs) or cap the history depth.
- Pairing with Command: in undo systems, Memento is good at saving "state" while Command is good at saving "operations." Complex editors often combine them: commands record what happened, mementos save and restore wholesale when needed.
Game saves, database transaction rollback, and an IDE's local history all carry Memento's shadow.
Loading practice...