Memento lets an object save its state into a separate snapshot object and later restore itself from it, without showing that state to anyone else. The object that owns the state (the originator) makes the snapshot and reads it back; whoever keeps the snapshots (the caretaker) only stores them. It is the pattern behind snapshot-based undo, checkpoints, save games and "roll back to here" features, and it is how you get those without making every private field public.
Think of it like
A sealed envelope at the coat check
Before a long hike you write down exactly where everything in your backpack goes, seal the note in an envelope and hand it to the lodge's front desk. The desk (the caretaker) files your envelope with everyone else's, in order, and hands back the newest one when you ask. It never opens it: it does not need to know what is inside, and you would not want it to. Only you (the originator) can read the note and put the backpack back the way it was. If you start keeping an inventory of a new pocket, you change what you write in the note; the front desk's filing system stays exactly the same.
The problem
A small text editor has a text and a font size. Users want undo, so a History class saves the editor's state before risky edits and puts it back on request. The quickest way to write History is to let it read and write the editor's fields itself, keeping one stack per field. That only works if those fields are public. This is the Before version in the visualizer above.
class Editor {
text = ""; // public for History
size = 12; // public for History
type(s: string) { this.text += s; }
resize(n: number) { this.size = n; }
}
class History {
private texts: string[] = [];
private sizes: number[] = [];
save(e: Editor) {
this.texts.push(e.text);
this.sizes.push(e.size);
}
undo(e: Editor) {
if (!this.texts.length) return;
e.text = this.texts.pop()!;
e.size = this.sizes.pop()!;
}
}- Encapsulation is gone.
textandsizeare public only so that undo can copy them, so now any class can also change them, skipping whatever rulesEditorwould enforce (a maximum size, a cursor that must stay inside the text). - The caretaker knows the originator's insides.
Historymust list every field ofEditor. Add a field and you must remember to add a stack, a line insave()and a line inundo(). Forget them and everything still compiles: undo just silently stops restoring that field. - Parallel stacks can drift. One array per field must stay exactly in step. A bug that pushes to one and not the other restores a text with the wrong size, and nothing detects it.
- The knowledge spreads. Autosave, crash recovery and "revert to last saved" are more caretakers, and each one would copy the same field list.
The pattern
Intent: without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. That is the Gang of Four's definition, almost word for word; the book also calls the pattern Token, because to everyone but its creator a memento is just an opaque token.
- Originator (
Editor) - The object whose state is saved. It creates a memento holding a copy of its current state (
save()) and sets its state back from one (restore(s)). It is the only class that knows what a memento contains. - Memento (
Snapshot) - A small, passive object that holds a copy of the originator's state at one moment. It should never change after it is created, and only the originator should be able to read it.
- Caretaker (
History) - Keeps mementos and hands them back when asked: a stack for undo, a list of checkpoints, a set of save slots. It never reads or changes what is inside one.
- Client
- Decides when to save and restore (before an edit, on Ctrl+Z). Here, the client program at the bottom of the code panel.
The key idea is that a memento has two interfaces. The caretaker sees a narrow one: something it can store, order and hand back, maybe with a label or a timestamp. The originator sees a wide one: every field it needs to rebuild itself. How you get two views of one object depends on the language (a nested class, a friend, a module-private type), and the Variations section shows each.
What the visualizer shows
- How to use it: press Play in the visualizer at the top of the page, or step with the arrow buttons. It really runs the classes in the code panel and draws what happened; the caption under the stage explains every step.
- Class diagram:
Editorhas a dashed creates arrow toSnapshot, andHistoryholds snapshots (the aggregation marked0..*).Historyhas no line toEditorat all.Snapshot's fields are marked~, UML's package visibility: meant for the editor's own code, not for the caretaker. (TypeScript has no package scope, so hereHistorysimply never reads them; Variations shows stricter ways.) - Objects at runtime (the undo timeline):
historyshowsstack = [s1, s2]with an arrow to each snapshot, oldest first. Each snapshot box holds the frozen copy it was given:s1keepstext = "Hi",size = 12ands2keepstext = "Hi yo",size = 12, whileeditormoves on to"Hi yo!"at size 18. On restore,editor's two fields change back together in one step. - Sequence of calls: the client calls
editor.save(), getss1back, and passes it tohistory.push(s1). On undo,history.pop()returnss2and the client hands it toeditor.restore(s2).historynever callseditor. - Before / With Memento and Add cursor: the toggle switches to the version where
Historyreads and writes the editor's public fields; itsundo()step showseditor's fields changing whilehistory's method runs. Add cursor applies the change request to whichever version is shown; touched classes get a badge (such asedited +12 −1), and the Change request panel beside the code compares both versions. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Create the originator and the caretaker
With With Memento selected, the client creates
editor(text = "",size = 12, both private) andhistory(stack = []). - 2
Edit, then save a checkpoint
editor.type("Hi")setstext = "Hi". Thenhistory.push(editor.save()):save()createss1, aSnapshotholding"Hi"and12, and returns it;push(s1)makes the stack[s1]. - 3
Edit and save again
type(" yo")makes the text"Hi yo", and a second save createss2("Hi yo",12). The stack is[s1, s2]: the undo timeline, oldest first. - 4
Keep editing
resize(18)andtype("!")change the editor to"Hi yo!"at size 18. The snapshots do not change: each holds its own copy of the values, not a reference to the editor. - 5
Undo: the caretaker hands back a token
history.pop()removes and returns the newest snapshot,s2. The stack is[s1].Historynever looked insides2, and its code would be the same whatever a snapshot contains. - 6
Restore: the originator reads its own memento
editor.restore(s2)copies the values back:textbecomes"Hi yo"andsizebecomes12in the same step. Another undo would restores1("Hi"at size 12). - 7
Compare with Before
Switch to Before:
Historyhastextsandsizesarrays,save(editor)copies each field, andundo(editor)writes them back intoeditorfrom outside. The result is the same text and size, but only becauseEditor's fields are public. - 8
Add cursor (change request)
With Add cursor applied, the editor gains a
cursor(typing inserts at it). With Memento,Snapshotcarries a third value andHistoryis unchanged; undo brings the cursor back from 6 to 5. Before,Historyneeds a third array and a line in both methods.
Before and after
Without the pattern
Editor's fields are public soHistorycan copy themHistorylists every editor field, one stack each- Restoring writes the editor's fields from outside the class
- A new field means edits in
Historytoo; forgetting compiles - Fewer classes; fine for a throwaway script
With Memento
Editor's state stays privateHistorystores opaque snapshots and never reads them- Only
Editordecides what is saved and how it is restored - A new field changes
Editorand its ownSnapshotonly - One more small class, and a copy of the state per snapshot
| Change request: add a cursor that undo restores | Before | With Memento |
|---|---|---|
| Existing classes edited | 2 (Editor, History) | 2 (Editor, Snapshot) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 14 (Editor +10 −1, History +3 −0) | 14 (Editor +12 −1, Snapshot +1 −0) |
| Classes touched | 2 | 2 |
The numbers are a tie, and that is honest: a new piece of state has to be declared and copied somewhere. The difference is where. With Memento, both edits are on the originator's side: Snapshot belongs to Editor (in Java it would be a nested class inside it), and save() and restore() sit next to the field they copy, so they are hard to forget. History, and any other caretaker such as autosave, is not opened at all. Before, the change crosses a class boundary: the field becomes public in Editor, and its save and restore lines go into a different class whose author may not know the field exists.
Variations
Narrow and wide interfaces in each language
| Language | Technique | What the caretaker can do |
|---|---|---|
| Java | The memento is a private nested class (or record) of the originator, exposed through an empty or label-only interface | Hold and pass the interface type; it cannot name the nested class, so it cannot read the fields |
| C++ | All members of the memento are private, and it declares friend class Editor; | Store and copy it; only the friend can construct it or read its members (this is the Gang of Four's own sample) |
| C# | A private nested class implementing a public marker interface | Same as Java |
| TypeScript | Callers get a narrow interface (Snapshot { label }) while the class with the fields stays unexported; or the snapshot is an empty token and the originator keeps the data in a private WeakMap keyed by it | Only what the narrow type declares; a cast could still get around a plain interface, the WeakMap version cannot be read at all |
| Python | A frozen dataclass with a leading underscore (_EditorState) to mark it private to the module | Anything, technically: privacy is a convention, so it relies on discipline and code review |
Snapshot has public readonly fields and History simply never reads them. The implementations below use the stricter techniques.Full snapshot or incremental changes
The visualizer's snapshots copy the whole state. That is the simplest and most robust choice: any snapshot can be restored on its own, in any order. For large state (a long document, an image, a game world) copying everything at every checkpoint is too expensive, so mementos can store only what changed since the previous one. The Gang of Four describe this too: when mementos are created and restored in a predictable order, as in undo, each can hold an incremental change. The price is that they must be applied strictly in sequence, and that a change record is, in effect, a command (see Command).
- Full snapshots: simple, restore in one step, memory grows with state size times history length.
- Diffs (incremental mementos): small, but restoring an old point means applying several in order, and one lost diff breaks the chain.
- Both: a full snapshot every N steps plus diffs in between, so restoring needs at most N diffs. Version control systems, databases and video codecs use the same trade-off (keyframes plus deltas).
- Bound the history either way. A caretaker does not know how big a memento is (the Gang of Four list this as a hidden cost), so "save before every keystroke" can quietly hold megabytes of copies. Cap the number of snapshots and drop the oldest (the second implementation uses a cap of 2 to show it), cap their total size, or merge checkpoints taken close together.
Immutable mementos and structural sharing
A memento must not change after it is made. If Snapshot held a reference to the editor's live list of paragraphs instead of a copy, the next edit would change the "saved" state too, and undo would restore the present. So either copy mutable parts deeply when saving (the same shallow vs deep copy question as in Prototype), or make the state immutable in the first place. Immutable state has a second benefit: if every change produces a new state object that shares the unchanged parts with the old one, keeping the old one as a memento costs almost nothing.
type Doc = Readonly<{
title: string;
paragraphs: readonly string[];
}>;
let doc: Doc = { title: "Notes", paragraphs: ["a", "b", "c"] };
const history: Doc[] = [];
function edit(change: (d: Doc) => Doc) {
history.push(doc); // the snapshot: no copying at all
doc = change(doc);
}
edit((d) => ({ ...d, title: "Plan" }));
// The new doc shares the same paragraphs array with the old one.
console.log(doc.paragraphs === history[0].paragraphs); // true
doc = history.pop()!; // undo
console.log(doc.title); // "Notes"This is how state containers with time travel work. Redux requires reducers to return new state objects instead of mutating the old ones, so Redux DevTools can keep the earlier states and jump back to any of them. Immer's produce() lets you write code that looks like mutation and returns a new immutable state that reuses every untouched branch of the old one. Persistent collections (Clojure's vectors and maps, Immutable.js) push the same idea down into the data structure. Git stores every commit as a snapshot of the whole tree, but an unchanged file is stored once and shared by every commit that contains it.
Memento and Command for undo
| Undo by | Memento | Command |
|---|---|---|
| What is stored | The state before (or after) a change | The operation, plus what it needs to reverse itself |
| How undo works | Put the old state back | Run the inverse operation, or put back the fragment the command overwrote |
| Cost per step | Proportional to the state size (unless shared or incremental) | Proportional to the change, usually small |
| Correctness | Always exact: no inverse to get wrong | Each command's undo() must be a true inverse |
| Redo | Keep the state you undid from | Run execute() again |
| Best when | Changes are hard to invert, or the state is small | State is large and changes are small and invertible |
They combine well. The Gang of Four note that commands can use mementos to keep the state an undo needs: a command whose effect has no clean inverse (apply a blur filter, run an auto-format) takes a memento of what it is about to change before execute(), and its undo() restores it. Large editors often mix both, using small command-based undo for typing and occasional full snapshots so that undoing far back does not mean reversing thousands of commands one by one.
Serialization and save games
A memento does not have to live in memory. Written to disk it becomes a save file, a draft that survives a browser refresh, or a checkpoint that a long-running job resumes from after a crash. The originator still decides the format; the storage layer (the caretaker) still just stores bytes. A few things need care, especially once mementos leave the process:
- Versioning. A save written by version 1 will be loaded by version 2, which may have new fields. Put a version number in the memento and teach
restore()to fill in defaults for older ones. - Encapsulation on disk. A serialized memento is readable (and editable) by anyone with the file. That is fine for undo, but sign or validate save files if players or users should not be able to tamper with them, and never deserialize untrusted bytes with a mechanism that can build arbitrary objects (Java's built-in serialization and Python's
pickleboth warn about this). - Resources are not state. Open files, sockets, database connections and timers do not round-trip through a snapshot, in memory or on disk. Save their description (a path, a URL, an offset) and let
restore()reopen them.
In real code
| Where | The memento | The caretaker |
|---|---|---|
| Android | View.onSaveInstanceState() returns a Parcelable; an activity writes its UI state into a Bundle in onSaveInstanceState() | The system keeps it while the activity is destroyed (rotation, process death) and hands it back to onRestoreInstanceState() or onCreate() |
| JDBC | Connection.setSavepoint() returns a java.sql.Savepoint | Your code holds it and later calls connection.rollback(savepoint); only the driver and database know what it refers to |
| SQL databases | SAVEPOINT name inside a transaction | ROLLBACK TO SAVEPOINT name undoes everything after it without ending the transaction (see ACID, BASE & Isolation Levels) |
| Browsers | The state object passed to history.pushState(state, "", url) | The browser stores a copy with each history entry and returns it in the popstate event when the user goes back |
| Redux DevTools | Each earlier state of the store | The DevTools keep the list and let you jump to any point (time-travel debugging) |
| Editors and design tools | Snapshots of a document or of the part a change touched | The undo stack, often mixed with command-based undo for small edits |
| Games and emulators | Save games and save states: the game's (or the whole emulated machine's) state at one moment | Save slots, checkpoints, quick-save files |
| Java and Python | An object graph written with ObjectOutputStream (classes that implement java.io.Serializable) or with pickle | A file or a cache; the bytes are restored with ObjectInputStream or pickle.load (only from trusted sources) |
When to use it, and when not to
Reach for Memento when
- You need undo, checkpoints or "revert", and restoring the whole state is simpler than inverting each operation
- Operations have no clean inverse (filters, formatting, game physics)
- Something outside the object must keep the saved states, but should not see or depend on what is in them
- You want to try something and roll back if it fails (a transaction-like
tryon an in-memory model)
Think twice when
- The state is large and changes are small and frequent: store commands or diffs instead
- The state is already immutable: just keep the old references, no extra class needed
- Part of the state is external (files, network, other services): a snapshot cannot roll that back
- Only one value is ever saved: a plain local variable may be enough
Memento vs similar patterns
| Pattern | What it keeps | Key question | Difference from Memento |
|---|---|---|---|
| Memento | An opaque copy of an object's state | What did this object look like before? | (The reference row.) Only the originator can read it |
| Command | An operation, with what it needs to undo it | What was done, and how is it reversed? | Stores the change, not the state; commands often hold mementos for undo |
| Prototype | A full, working copy of an object | How do I make another object like this one? | A clone is a live object anyone can use; a memento is a passive record only its originator can read |
| State | The object's current mode, as an object | How should it behave right now? | State changes behavior; a memento saves data to bring back later |
| Iterator | A position inside a traversal | Where am I in this collection? | An iterator's position is state, and a saved cursor or page token is a memento of the iteration |
| Event Sourcing | Every change, as an event, in order | How did we get here? | Rebuilds state by replaying events; snapshots (mementos) are often added so replay starts from a recent point |
Implementation
The scenario with the change request applied: an Editor with private text, size and cursor, a Snapshot memento the caretaker cannot read, and a History caretaker with push and pop. Each language enforces the narrow interface its own way: an unexported class behind a label-only interface in TypeScript, a private nested record in Java, a module-private frozen dataclass in Python, and a friend class in C++. The demo saves twice, moves the cursor and edits, then undoes twice and shows what happens when the history is empty.
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class _EditorState:
"""The memento. The leading underscore says "private to this module":
Python cannot enforce it, so the caretaker keeps out by convention.
frozen=True makes it immutable."""
label: str
text: str
size: int
cursor: int
class Editor:
"""The originator: its state lives in "private" fields."""
def __init__(self) -> None:
self._text = ""
self._size = 12
self._cursor = 0
self._saves = 0
def type(self, s: str) -> None:
t, c = self._text, self._cursor
self._text = t[:c] + s + t[c:]
self._cursor = c + len(s)
def move_to(self, i: int) -> None:
self._cursor = max(0, min(i, len(self._text)))
def resize(self, n: int) -> None:
self._size = n
def save(self) -> object: # callers only get an opaque object
self._saves += 1
return _EditorState(f"#{self._saves}", self._text, self._size,
self._cursor)
def restore(self, s: object) -> None:
if not isinstance(s, _EditorState):
raise TypeError("not a snapshot of an Editor")
self._text, self._size, self._cursor = s.text, s.size, s.cursor
def __str__(self) -> str:
t, c = self._text, self._cursor
return f'"{t[:c]}|{t[c:]}" at size {self._size}'
class History:
"""The caretaker: keeps snapshots in order and never looks inside."""
def __init__(self) -> None:
self._stack: list[object] = []
def push(self, s: object) -> None:
self._stack.append(s)
def pop(self) -> object | None:
return self._stack.pop() if self._stack else None
def __len__(self) -> int:
return len(self._stack)
editor = Editor()
history = History()
def undo() -> None:
last = history.pop()
if last is not None:
editor.restore(last)
else:
print("nothing to undo")
editor.type("Hi")
history.push(editor.save()) # 1
editor.type(" yo")
history.push(editor.save()) # 2
editor.resize(18)
editor.move_to(2)
editor.type(",")
print("now: ", editor) # "Hi,| yo" at size 18
print("saved:", len(history)) # 2
undo()
print("undo: ", editor) # "Hi yo|" at size 12
undo()
print("undo: ", editor) # "Hi|" at size 12
undo() # nothing to undoKey takeaways
- Memento saves an object's state in a separate snapshot object so it can be restored later, without making that state public.
- Three roles: the originator creates mementos and restores from them, the memento holds a frozen copy, and the caretaker stores mementos without looking inside.
- A memento has a narrow interface for the caretaker and a wide one for the originator; languages provide it with nested private classes, friends, unexported types or naming conventions.
- Mementos must be immutable copies. With immutable state and structural sharing (Redux, Immer, persistent collections), a snapshot is just a reference to the old state.
- For the "add a cursor" request, both versions edit 2 classes and 14 lines; with Memento both edits stay on the originator's side and
Historyis untouched. - Memento stores state, Command stores operations. Snapshots are simple and always exact but cost memory; real undo systems often combine both and cap the history.
Common pitfalls
- Shallow snapshots: copying a reference to a mutable list or object instead of its contents, so later edits change the saved state too. Copy deeply, or keep the state immutable.
- Letting the caretaker read or modify mementos ("just add a getter"), which brings back exactly the coupling the pattern removes.
- Unbounded history: a snapshot of a large state on every keystroke exhausts memory. Cap by count or size, merge nearby checkpoints, or store diffs.
- Saving state the snapshot cannot really restore: open files, connections, timers, or data owned by other objects that changed in the meantime.
- Persisted mementos without a version number, so a save from an older release cannot be loaded, or loads with fields silently missing.
Interview tips
- Define it with the encapsulation clause: "capture and restore an object's internal state without exposing it". Then name the three roles and draw the narrow and wide interfaces.
- Expect "Memento or Command for undo?": state vs operation, memory vs inverse correctness, and that they combine (a command can hold a memento).
- Bring up the production concerns unprompted: bounding the history, immutability (or deep copies), incremental snapshots for big state, and versioning when snapshots are persisted.
Real-world applications
- Snapshot-based undo and redo in editors, drawing tools and spreadsheets.
- Save games, checkpoints and emulator save states.
- Draft autosave and restoring form or screen state after a reload or a mobile app being killed (Android's saved instance state).
- Transaction savepoints and rollback, in databases and in in-memory models (try a change, roll back on failure).
- Time-travel debugging and state history in front-end state containers (Redux DevTools).
- Checkpoints in long-running jobs and simulations, so they can resume after a crash.
Test yourself
In the visualizer, history.stack is [s1, s2] and the client undoes. What happens?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.