What is the Memento Pattern?
Learn the Memento design pattern — Originator, Memento, Caretaker roles and undo support — with a Java example and interview Q&A.
Expected Interview Answer
The Memento pattern captures and externalizes an object’s internal state so it can be restored later, without violating encapsulation by exposing that state’s structure to the code that stores it.
Three roles cooperate: the Originator, which creates a Memento snapshot of its own current state and can restore itself from one; the Memento itself, an opaque object that holds the captured state but exposes no public methods for outside code to inspect or modify it; and the Caretaker, which requests and stores mementos (often in a history stack) but never looks inside them. Because only the Originator can read a Memento’s contents, encapsulation is preserved even though state is being handed outside the object that owns it — this is typically achieved with a private inner class or package-private access. The pattern is the standard mechanism behind undo/redo history, checkpoint/rollback systems, and save-game functionality, and it pairs naturally with the Command pattern, where each command’s undo() restores a memento captured before execution.
- Enables undo/redo and checkpoint/rollback without breaking encapsulation
- Keeps state-capture logic inside the Originator, not scattered externally
- Lets the Caretaker manage history (stacks, timelines) without knowing state internals
- Composes cleanly with the Command pattern for undoable operations
AI Mentor Explanation
Before a risky declaration, a captain has the scorer save a sealed snapshot of the current score, overs, and wickets — a memento — that only the team’s own analyst can later open and use to restore exactly where the innings stood. The twelfth man (caretaker) just carries the sealed envelope around and knows when to hand it back, without ever peeking inside it. If the declaration backfires, the captain restores the innings from that snapshot, exactly the way an Originator restores its state from a Memento it alone can interpret.
Step-by-Step Explanation
Step 1
Define the Originator
The object whose state needs saving; it creates and restores from Memento snapshots of itself.
Step 2
Define the Memento
An opaque snapshot object exposing no public way for outside code to read or modify its contents.
Step 3
Define the Caretaker
Stores and manages mementos (e.g. in a history stack) without ever inspecting what is inside them.
Step 4
Save and restore
Originator.save() produces a memento handed to the Caretaker; Originator.restore(memento) reverts its own state later.
What Interviewer Expects
- A clear definition: capturing and restoring state without breaking encapsulation
- The three roles: Originator, Memento, Caretaker, and their responsibilities
- Awareness that the Caretaker never inspects memento internals
- A concrete use case: undo/redo, checkpoints, save-game systems
Common Mistakes
- Letting the Caretaker read or modify memento internals, breaking encapsulation
- Confusing Memento with simply serializing an object to JSON with no access control
- Storing unbounded memento history without any eviction, causing memory growth
- Not realizing Memento pairs naturally with Command for implementing undo()
Best Answer (HR Friendly)
“The Memento pattern lets an object save a snapshot of its own current state so it can be restored later, without letting the code holding onto that snapshot peek inside or tamper with it. It’s the mechanism behind undo buttons and save-game files — the object that owns the state is the only one that can fully read or restore that snapshot.”
Code Example
class EditorMemento {
private final String content;
EditorMemento(String content) { this.content = content; }
private String getContent() { return content; } // package-private, only Editor reads it
}
class Editor {
private String content = "";
void type(String text) { content += text; }
String getContent() { return content; }
EditorMemento save() { return new EditorMemento(content); }
void restore(EditorMemento memento) { this.content = memento.getContent(); }
}
class History {
private final java.util.Deque<EditorMemento> stack = new java.util.ArrayDeque<>();
void push(EditorMemento m) { stack.push(m); }
EditorMemento pop() { return stack.pop(); }
}
Editor editor = new Editor();
History history = new History();
editor.type("Hello");
history.push(editor.save());
editor.type(", world!");
editor.restore(history.pop()); // back to "Hello"Follow-up Questions
- How does the Memento pattern avoid breaking encapsulation?
- How does Memento typically pair with the Command pattern for undo?
- What are the memory-cost tradeoffs of storing many mementos?
- How would you implement redo alongside undo using mementos?
MCQ Practice
1. What is the primary purpose of the Memento pattern?
Memento snapshots an Originator’s state into an opaque object that can later restore it, preserving encapsulation.
2. Which role is responsible for storing mementos without inspecting their contents?
The Caretaker holds onto mementos, often in a history stack, but never reads or modifies what is inside them.
3. Which pattern does Memento most naturally pair with to implement undo()?
A Command’s undo() often restores a memento captured before the command executed, combining the two patterns cleanly.
Flash Cards
Memento pattern in one line? — Capture an object’s state in an opaque snapshot that only the object itself can restore from.
Three roles? — Originator (owns state), Memento (opaque snapshot), Caretaker (stores mementos without reading them).
Why doesn’t this break encapsulation? — The Memento exposes no public way for outside code to read or modify its captured state.
Common real-world use? — Undo/redo history, checkpoint/rollback systems, and save-game functionality.