Memento Pattern
A Memento is a snapshot of an object’s state that the object itself produces and the object itself consumes. Anyone can hold that snapshot, keep a stack of them, pass them around and hand one back – but nobody except the originating object can read inside one. That asymmetry is the entire pattern. The undo stack gets to store your state without ever learning what your fields are called.
💡 Originator = the object whose state gets captured, and the only class that may read a snapshot. Memento = the opaque snapshot itself. Caretaker = whoever holds the snapshots, usually the undo stack, and is deliberately unable to open them.
Why this matters: undo turns up in a text editor, a spreadsheet, a version-control clone and half the board-game and drawing prompts, and nearly every candidate’s first answer is the same – a history list that stores copies of the object’s public fields. That answer compiles. Then the interviewer asks what happens when you add a field, whether the restore path runs the same validation as a real user edit, and whether a 10 MB document can afford a snapshot per keystroke. What gets graded is not whether you can name the pattern. It is whether the snapshot is genuinely opaque, whether it is deep enough to be a snapshot at all, and whether you can state a rule – not a shrug – for when to save state versus when to log the operation.
Prerequisites
- Immutability and Equality – a snapshot that can change after it is taken is not a snapshot, so this pattern is mostly immutability with a purpose
- Command Pattern – the other half of every undo answer. Memento stores the state after; Command stores the operation and its inverse
- Prototype Pattern – deep versus shallow copying is the same question here, and the shallow version is the same bug
The Problem: the undo stack that knows your fields
Here is undo built the obvious way. Editor grows getters so the history can read it, setters so the history can put it back, and a Snapshot in the middle that is a bag of public fields anyone can touch:
public class Editor { // every field needs a getter AND a setter
private String text = "";
private int cursor = 0;
private int selectionStart = -1;
public String getText() { return text; }
public int getCursor() { return cursor; }
public int getSelectionStart() { return selectionStart; }
public void setSelectionStart(int s) { this.selectionStart = s; }
public void setText(String text) {
this.text = text;
fireDocumentChanged(); // spell-check, autosave, word count all listen
}
public void setCursor(int cursor) {
if (cursor < 0 || cursor > text.length()) // validation written for typing
throw new IndexOutOfBoundsException("cursor " + cursor);
this.cursor = cursor;
}
}
// A bag of public fields with a public constructor. Nothing says "snapshot".
public class Snapshot {
public String text;
public int cursor;
public int selectionStart;
public Snapshot(String t, int c, int s) { text = t; cursor = c; selectionStart = s; }
}
public class EditorHistory {
private final Deque<Snapshot> undo = new ArrayDeque<>();
public void record(Editor editor) {
undo.push(new Snapshot(editor.getText(), // the history does the reading
editor.getCursor(),
editor.getSelectionStart()));
}
public void undo(Editor editor) {
Snapshot s = undo.pop();
editor.setText(s.text); // fires documentChanged
editor.setCursor(s.cursor); // validates against the NEW text
editor.setSelectionStart(s.selectionStart);
}
}
Three costs, and an interviewer will go after all three:
- The editor’s internals are now its public API, and
EditorHistorydepends on them. Every field that counts as editor state has to be readable and writable from outside. Worse, adding a field breaks undo silently: put ascrollOffsetonEditorandrecorddoes not capture it,undodoes not restore it, nothing fails to compile and nothing throws. Undo quietly leaves the viewport somewhere the user never was. - Restore runs through setters built for a different job.
setTextfiresdocumentChanged, so undo triggers autosave and spell-check as though a human typed.setCursorvalidates against the current text length, so the order of those three calls decides whether a legal snapshot restores or throws – shrink the text, restore the old cursor first, and undo itself raises. Whatever set this state originally did none of that. - Nothing stops the caretaker mutating or forging a snapshot.
Snapshot.textis a public field on an objectEditorHistoryowns outright, so any code holding it can rewrite history in place. And since the constructor is public,new Snapshot("", 0, -1)is a valid “previous state” the editor was never in.
Class Diagram
classDiagram
class EditorMemento {
<<interface>>
}
class Editor {
-StringBuilder buffer
-int cursor
-List~Bookmark~ bookmarks
+type(String s)
+save() EditorMemento
+restore(EditorMemento m)
}
class Snapshot {
-String text
-int cursor
-List~Bookmark~ bookmarks
}
class History {
-Deque~EditorMemento~ undoStack
-Deque~EditorMemento~ redoStack
-int maxDepth
+backup(Editor e)
+undo(Editor e)
+redo(Editor e)
}
EditorMemento <|.. Snapshot
Editor ..> Snapshot : creates and reads
Editor ..> EditorMemento : returns
History --> EditorMemento
History ..> Editor : calls save and restore
The non-obvious part is that EditorMemento has no members at all, and that is the enforcement mechanism rather than an omission. Snapshot is a private nested class of Editor, so History can name the interface, store it and hand it back, but has no type it could cast to in order to reach a field. History points at Editor only to call save and restore; it never reads editor state directly either.
Real-World Example: Text Editor with Undo and Redo
import java.util.*; // ArrayDeque, ArrayList, Deque, List
/** The memento as the world sees it: no methods, because there is nothing a
* caretaker may ask a snapshot. */
public interface EditorMemento { }
public record Bookmark(String name, int offset) { } // immutable, so safe to share
public class Editor {
private final StringBuilder buffer = new StringBuilder();
private int cursor = 0;
private final List<Bookmark> bookmarks = new ArrayList<>();
private final ChangeListeners listeners = new ChangeListeners();
// ---- The real memento: private, nested, immutable, final ----
private static final class Snapshot implements EditorMemento {
private final String text;
private final int cursor;
private final List<Bookmark> bookmarks;
private Snapshot(String text, int cursor, List<Bookmark> marks) {
this.text = text; // String is immutable: safe to share
this.cursor = cursor;
this.bookmarks = List.copyOf(marks); // a COPY, not the live list
}
}
// Only Editor can build a Snapshot, because only Editor can see the type.
public EditorMemento save() {
return new Snapshot(buffer.toString(), cursor, bookmarks);
}
// Writes its own fields directly: no setters, so none of the validation
// meant for typing and none of the events meant for user edits.
public void restore(EditorMemento memento) {
if (!(memento instanceof Snapshot s)) {
throw new IllegalArgumentException("memento not produced by this Editor");
}
buffer.setLength(0);
buffer.append(s.text);
cursor = s.cursor;
bookmarks.clear();
bookmarks.addAll(s.bookmarks);
listeners.documentReplaced(); // ONE event for the restore, not one per field
}
public void type(String s) {
buffer.insert(cursor, s);
cursor += s.length();
listeners.documentChanged(); // the event a real edit fires
}
public String text() { return buffer.toString(); }
}
/** Caretaker: stores mementos, orders them, hands them back, drops them. */
public final class History {
private final Deque<EditorMemento> undoStack = new ArrayDeque<>();
private final Deque<EditorMemento> redoStack = new ArrayDeque<>();
private final int maxDepth;
public History(int maxDepth) { this.maxDepth = maxDepth; }
/** Call immediately BEFORE a mutating operation. */
public void backup(Editor editor) {
undoStack.push(editor.save());
redoStack.clear(); // a fresh edit invalidates the redo branch
while (undoStack.size() > maxDepth) {
undoStack.removeLast(); // bounded history: drop the oldest snapshot
}
}
public void undo(Editor editor) {
if (undoStack.isEmpty()) throw new NothingToUndoException();
redoStack.push(editor.save()); // current state becomes the redo target
editor.restore(undoStack.pop());
}
public void redo(Editor editor) {
if (redoStack.isEmpty()) throw new NothingToRedoException();
undoStack.push(editor.save());
editor.restore(redoStack.pop());
}
// Neither of these compiles, and that IS the pattern:
// undoStack.peek().getText(); // EditorMemento has no methods
// ((Editor.Snapshot) undoStack.peek()); // Snapshot is private to Editor
// The caretaker is structurally incapable of reading what it holds.
}
// ---- Usage: back up BEFORE each mutation ----
History history = new History(100);
history.backup(editor); editor.type("hello");
history.backup(editor); editor.type(" world");
history.undo(editor); // text() == "hello"; redo() puts " world" back
from collections import deque
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class _Snapshot:
"""The memento.
frozen=True -> the caretaker cannot mutate a snapshot it holds.
slots=True -> generates __slots__, so a 1000-deep undo stack does not
also carry 1000 per-instance __dict__ objects.
bookmarks is a tuple, not a list: a list would alias live editor state.
"""
text: str
cursor: int
bookmarks: tuple[tuple[str, int], ...]
class Editor:
def __init__(self) -> None:
self._text = ""
self._cursor = 0
self._bookmarks: list[tuple[str, int]] = []
def type(self, s: str) -> None:
self._text = self._text[:self._cursor] + s + self._text[self._cursor:]
self._cursor += len(s)
def save(self) -> _Snapshot:
return _Snapshot(self._text, self._cursor, tuple(self._bookmarks)) # a copy
def restore(self, m: _Snapshot) -> None:
if not isinstance(m, _Snapshot):
raise TypeError("memento was not produced by an Editor")
self._text, self._cursor = m.text, m.cursor
self._bookmarks = list(m.bookmarks)
class History:
"""Caretaker. backup and undo mirror the Java tab exactly."""
def __init__(self, max_depth: int = 100) -> None:
# maxlen gives bounded history for free: appending past the cap evicts
# from the opposite end.
self._undo: deque[_Snapshot] = deque(maxlen=max_depth)
self._redo: list[_Snapshot] = []
def undo(self, editor: Editor) -> None:
if not self._undo:
raise LookupError("nothing to undo")
self._redo.append(editor.save())
editor.restore(self._undo.pop())
# Say this out loud in an interview: History *can* evaluate self._undo[-1].text.
# The underscore on _Snapshot plus frozen=True are a convention and a mutation
# guard, not an access guarantee -- name mangling only renames __text to
# _Snapshot__text. Python cannot enforce this pattern, only agree to it.
#include <deque>
#include <stdexcept>
#include <string>
#include <vector>
class Editor; // forward declaration so the memento can name its friend
// Every data member is private AND the only constructor is private, so this
// type is inert to everyone except the one class named at the bottom.
class EditorMemento {
std::string text_;
std::size_t cursor_;
std::vector<std::string> bookmarks_; // by value: a copy, never an alias
EditorMemento(std::string text, std::size_t cursor,
std::vector<std::string> bookmarks)
: text_(std::move(text)), cursor_(cursor),
bookmarks_(std::move(bookmarks)) {}
friend class Editor; // Editor may construct and read. Nobody else may.
};
class Editor {
std::string text_;
std::size_t cursor_ = 0;
std::vector<std::string> bookmarks_;
public:
void type(const std::string& s) { text_.insert(cursor_, s); cursor_ += s.size(); }
EditorMemento save() const { return EditorMemento(text_, cursor_, bookmarks_); }
void restore(const EditorMemento& m) {
text_ = m.text_; // compiles ONLY because of the friend declaration
cursor_ = m.cursor_;
bookmarks_ = m.bookmarks_;
}
};
// Caretaker. It holds mementos by value, moves them, orders them, drops them.
class History {
std::deque<EditorMemento> undo_;
std::deque<EditorMemento> redo_;
std::size_t maxDepth_;
public:
explicit History(std::size_t maxDepth = 100) : maxDepth_(maxDepth) {}
void backup(const Editor& e) {
undo_.push_back(e.save());
redo_.clear(); // new edit kills redo
if (undo_.size() > maxDepth_) undo_.pop_front(); // bounded: drop oldest
}
void undo(Editor& e) { // redo is the mirror image: swap the two deques
if (undo_.empty()) throw std::runtime_error("nothing to undo");
redo_.push_back(e.save());
e.restore(undo_.back());
undo_.pop_back();
}
// undo_.back().text_ -> error: 'text_' is a private member of
// 'EditorMemento'. One line, "friend class Editor", is the whole access
// policy, and the compiler checks it.
};
Read the C++ tab even if you will answer in Java. friend class Editor states the pattern’s central rule as one declaration the compiler checks – this class may look inside, no other class may – which makes it the cleanest expression of the caretaker-cannot-look rule of the three languages. Java gets there by a longer route; Python does not get there at all.
Full snapshots do not scale, and the fix is the pattern next door
Run the arithmetic. Suppose a 10 MB document and one save() per keystroke: buffer.toString() allocates a fresh 10 MB string each time, so typing at five characters a second allocates roughly 50 MB per second, and a 100-deep stack pins about a gigabyte. That is multiplication, not a benchmark, and it is why “snapshot everything” is wrong for a text editor and fine for a tic-tac-toe board.
Fix 1 – snapshot less often. One memento per command group rather than per character: at a word boundary, around a paste, around a find-and-replace, after a 500 ms idle gap. Nobody expects Ctrl+Z to walk back one letter at a time, so the product decision and the performance fix are the same decision.
Fix 2 – store the delta instead of the state. That is the Command pattern with an undo() on each command. InsertText(at: 412, "world") is undone by deleting five characters at offset 412, so memory tracks the edit rather than the document. The honest rule for choosing:
- Command / delta when operations are cheaply invertible and the state is large – text editing, drawing, CAD, anything where one edit touches a sliver of a big object.
- Memento / snapshot when the state is small, or when operations are not invertible. A random shuffle cannot be un-shuffled. A
format()that collapses whitespace has discarded the information its own inverse needs. Anything readingnow()or an RNG is not replayable forward either, so recomputing will not get you back. In those cases you had to keep the bytes, and a memento is how you keep them.
Fix 3 – make copying cheap with structural sharing. Put the document in a persistent (immutable) data structure – a rope, a persistent balanced tree, a HAMT – and a “copy” costs O(log n) instead of O(n), because every subtree the edit did not touch is shared by reference with the previous version. A snapshot is then a new root pointer plus the single changed path. That is copy-on-write, and it is why Mini Version Control can afford a whole-tree snapshot per commit: Git’s model is this idea, a commit pointing at a tree whose unchanged subtrees reuse the same object hashes.
💡 Structural sharing = two versions of a data structure physically sharing the parts that are identical, so a snapshot costs only the changed path. It requires immutability, since a shared node someone can mutate corrupts every version pointing at it.
The memento must be deep enough
This is the most common bug in a candidate’s undo implementation, so state it as a rule: a memento holding a reference to a mutable object the originator keeps editing is not a snapshot at all. Pass this.bookmarks instead of List.copyOf(this.bookmarks) and the snapshot stores the same list object. The editor appends a bookmark, the archived snapshot changes with it, and undo faithfully restores the present. It never throws, and it passes any test whose assertions only look at text.
Every reference inside a memento must therefore point at something immutable or at a copy made at save time. That is why Bookmark is a record, why the Python memento holds a tuple, and why the C++ one holds its std::vector by value. Making the state objects immutable up front is cheaper than remembering to copy them at every call site.
Memento vs Command vs Prototype vs Event Sourcing
All four capture something about an object so you can get back to it later. What differs is what gets captured, and what for:
| Pattern | Intent | Tell |
|---|---|---|
| Memento | Capture state so the originator can be put back into it | Stores the state after. Size tracks the object, not the edit |
| Command | Encapsulate an operation plus how to invert it | Stores the operation and its arguments. Useless unless undo() can be written |
| Prototype | Clone an object to produce another live object | The copy gets used and edited, not filed away. Same machinery, different purpose |
| Event Sourcing | Persist the operation log as the source of truth, derive state by replay | Current state is a projection you can delete and rebuild |
Prototype is the one people mis-sort, and the test takes a glance: if the copy is handed to a user to work on, it is a Prototype; if it is pushed onto a stack and never read, it is a Memento.
The practical overlap is Command and Memento, and the standard production answer is a hybrid rather than a choice: a log of commands or events for granularity and audit, plus a memento every N operations as a checkpoint so replay never starts from zero. That shape is everywhere – a database’s write-ahead log with periodic checkpoints, a game that records inputs and also autosaves, a version-control system whose commits are snapshots over a stream of changes.
When to Use vs When to Avoid
| Use Memento When | Avoid When |
|---|---|
| The state is small relative to how many operations you must undo | The state is large and every operation is cheaply invertible – use Command |
Operations are not invertible: a shuffle, a lossy format(), anything reading a clock or RNG |
You can deterministically and cheaply replay forward from the beginning |
| A multi-step transaction needs a checkpoint to roll back to when step four fails | The caretaker legitimately needs to read the state – you want a DTO or a projection |
| The originator’s fields must stay private while something outside holds its state | The object is already immutable, so the current reference is the memento |
| State must survive a boundary: a saved game, a wizard’s back button, a form draft | Per-operation snapshot cost is unbounded and you have no structural sharing |
Two failure modes, and the first is the one that ships. The shallow memento aliases live mutable state, as above: the archive mutates along with the present, undo restores the state you were trying to escape, and nothing throws. The second arrives months later and is harder to reverse. In memento-as-DTO, something outside the module needs the snapshot – the autosave writer, a crash-recovery file, an API returning “the document as of commit X” – so Snapshot sprouts public getters, picks up a serialization annotation, acquires a schemaVersion, and becomes a wire format with external consumers and a compatibility policy. Editor can then no longer rename or drop one of its own fields, which is exactly the coupling the pattern existed to prevent. Keep the memento opaque and let the originator own the export: Editor.toDocumentDto() builds a separate, explicitly versioned type, and the snapshot stays unreadable from outside.
Interview Questions
-
“Memento or Command for undo in a text editor?” – Command, and here is the rule rather than “it depends”: if the inverse of an operation can be computed from the operation plus O(edit size) of saved data, store the command; if not, store the memento. Typing, deleting and pasting all pass that test, and a 10 MB document makes per-keystroke snapshots unaffordable. But the same editor still needs mementos for the operations that fail it – reformat document, sort selected lines, shuffle – because their inverse needs the original bytes. The complete answer is both: commands for the invertible edits, plus a memento checkpoint every N commands so undoing 400 operations does not replay from an empty buffer.
-
“Python and JavaScript have no package-private access. How do you stop the caretaker reading the memento?” – Mostly you do not, and the honest answer is that this pattern’s encapsulation guarantee is language-dependent. C++ has
friend, checked by the compiler; Java has a private nested class behind a marker interface; Python has a leading underscore plus an agreement, since name mangling only renames__textto_Snapshot__text. Modern JavaScript is the exception –#textclass fields really are enforced at runtime. If Python must enforce it, return a closure fromsave()so the caretaker holds a callable with no readable fields, and accept that you gave up serialization, equality and a useful debugger view. -
“How do you bound undo memory?” – Cap the depth first, with
Deque.removeLast()or adeque(maxlen=n), because unbounded undo over a long session is a real leak and not a theoretical one. Then notice that a depth cap is not a memory bound when snapshot sizes vary by three orders of magnitude: the better policy is a byte budget, where each memento reports its retained size and you evict the oldest until you are under it. Two details people miss – clear the redo stack on a new edit or you hold two histories, and once you have gone hybrid, count edits since the last checkpoint rather than snapshots. -
“How does undo interact with concurrent or collaborative editing?” – Undo has to be per-user: each client keeps a stack of its own changes, because one global stack means Alice’s Ctrl+Z reverts Bob’s paragraph. Even then, undoing your edit after someone else changed the same region is a different problem, because the memento you saved describes a document that no longer exists and restoring it wholesale discards their work. Getting that right means transforming your inverse against the operations that landed after it, which is operational-transform or CRDT territory. Name it, say Memento is the wrong tool there, and do not design it at the whiteboard.
-
“If the caretaker cannot read a memento, what may it do with one?” – Store it, order it, hand it back, drop it. That short list covers undo, redo, checkpointing and rollback, which is why the marker interface can be empty. When you genuinely need more – a timestamp for a history-panel label, a retained size for eviction – expose a narrow interface of metadata about the snapshot (
takenAt(),retainedBytes()), never the state inside it. Anything the caretaker can read is something the originator has agreed to keep public forever.
See It in Action
- Text Editor – commands for the invertible edits,
EditorMementofor formatting and sorting plus periodic checkpoints - Mini Version Control – a commit is a memento of the whole working tree, affordable because unchanged subtrees are shared
- Spreadsheet Engine – snapshot a cell’s formula and cached value before recalculation, so a cycle or an evaluation error can roll the sheet back