Behavioral 9 — Memento
In one line
Save a snapshot of an object's state so you can restore it later, without exposing its private fields. Think 'save game' in a video game.
Think of it like this
The save point in a video game. You save before the boss fight; if you lose, you load the save and everything is exactly as it was.
Key ideas
- 01
Three roles: Originator (the object that has state, e.g. the editor), Memento (the sealed snapshot), Caretaker (keeps the list of snapshots, e.g. the history).
- 02
The caretaker can store and hand back mementos but can't read or change what's inside them. That keeps encapsulation intact.
- 03
Command vs Memento for undo: Command stores 'how to reverse the action' (small, but every action needs an undo). Memento stores 'the whole state before' (simple, but uses more memory).
- 04
Used in: text editor undo, game checkpoints, form drafts, and transaction rollback in a database.
Java / Spring map
- →
A Java record makes a perfect immutable memento. Serialization-based snapshots are the heavy version.
Code & diagrams
Editor snapshots: save, change, restore.
// Originator
public final class Editor {
private String text = "";
private int cursor = 0;
public void type(String s) { text = text.substring(0, cursor) + s + text.substring(cursor); cursor += s.length(); }
public Snapshot save() { return new Snapshot(text, cursor); } // create memento
public void restore(Snapshot s) { this.text = s.text(); this.cursor = s.cursor(); }
// Memento: immutable; only Editor knows what the fields mean
public record Snapshot(String text, int cursor) {}
}
// Caretaker
public final class History {
private final Deque<Editor.Snapshot> saves = new ArrayDeque<>();
public void push(Editor.Snapshot s) { saves.push(s); }
public Editor.Snapshot pop() { return saves.pop(); }
}
// Editor e = new Editor(); History h = new History();
// e.type("Hello"); h.push(e.save());
// e.type(" World"); e.restore(h.pop()); // back to "Hello"Explain without notes
When would you choose Memento over Command for undo, and vice versa?
Practice
Add checkpoints to the Tic-Tac-Toe LLD so a player can take back the last move.
Trade-offs
- ↔
Full snapshots are simple but use lots of memory for big objects. Keep a cap on history, or store diffs instead.
Completion checklist
I can name the three roles and implement save/restore without exposing private fields.