Capture an object's internal state in a snapshot object so the object can be returned to that state later, without exposing its internals to the code that stores the snapshot.
Memento lets an object hand out a sealed snapshot of its own state and later rebuild itself from that snapshot. The code that holds the snapshot can store it, label it and pass it back, but it cannot read or change what is inside. This guide works through one scenario: a seating planner for event organisers. Its auto-seater tries a table for a group of guests, checks the result and rolls back when the attempt fails. In an interview you should be able to explain the three roles (originator, memento, caretaker), show why a public getter for the internal state does not solve the same problem, and discuss what snapshots cost in memory.
The problem
A situation where the obvious design starts to hurt.
You work on Tablewise, the seating module of an events platform. An organiser preparing a 140-guest charity gala has 14 tables of 10 seats and 52 parties: families, couples and work groups that must sit together. There are also keep-apart rules, such as two former business partners who should not share a table.
The auto-seater places one party at a time. For each party it tries tables in order, seats the members one by one, then checks the keep-apart rules. When a table fills halfway through a party, or a rule is broken, the attempt has to be undone completely.
The first version undid attempts by hand. The auto-seater remembered which guests it had just placed and called unseat() for each one. That worked until someone added a waiting-list counter and a per-table dietary tally to SeatingPlan. The manual undo did not reset either, so a failed attempt left the counters wrong and the gala plan reported 11 vegetarian meals at a table with 9 guests.
The second idea was to add getAssignments() and setAssignments() so the auto-seater could copy the map before an attempt and write it back afterwards. That makes the plan's internal structure part of its public API. Any caller can now put the plan into an invalid state, for example 12 guests at a 10-seat table. Every future change to the plan's fields also breaks the auto-seater.
The solution
What the pattern proposes.
Let SeatingPlan take its own snapshots. It gets two methods: save(label) returns a PlanSnapshot, and restore(snapshot) puts the plan back exactly as it was when that snapshot was taken.
PlanSnapshot is the memento. Publicly it shows only harmless metadata: a label and how many guests were seated. The actual assignment map is kept where only SeatingPlan can reach it. In the code below this is a private weak map inside the plan, keyed by snapshot object, which works the same way in TypeScript, Python and PHP. Because it is a weak map, a snapshot that the caretaker drops is garbage-collected together with its copied state. It also means a plan refuses snapshots taken from a different plan.
AutoSeater is the caretaker. Before each attempt it calls plan.save(), and if the attempt fails it calls plan.restore(checkpoint). It never needs to know what the plan contains. When someone adds a dietary tally to the plan, they update save and restore in the same class, and rollback keeps working everywhere.
An everyday analogy
The same idea, outside software.
Think of a coat check at a theatre. You hand over your coat and get a numbered ticket. The ticket tells you nothing about the coat: not its size, not what is in the pockets, not which hook it hangs on. You can carry the ticket around, lose it or give it to a friend, but the only thing you can do with it is hand it back to the attendant, who uses it to return exactly the coat you left. The attendant is the originator, the ticket is the memento, and you are the caretaker.
Structure
The pieces and how they relate.
Participants
- SeatingPlan (Originator)
- Owns the guest-to-table assignments and enforces capacity. It is the only class that can create a snapshot of its state or rebuild itself from one.
- PlanSnapshot (Memento)
- An immutable token for one moment of the plan. Its public surface is a label and a seated count. The real state is reachable only by the plan that created it.
- AutoSeater (Caretaker)
- Decides when to checkpoint and when to roll back while it tries tables for each party. It stores snapshots but never inspects or changes their contents.
- PlannerApp (Client)
- Starts auto-seating for a list of parties and shows the organiser the resulting plan.
Pseudocode
The solution to the scenario, language-neutral.
class PlanSnapshot
label, seatedCount // public metadata only
class SeatingPlan
private assignments: map guest -> table
private capacity: map table -> seats
private snapshots: weak map PlanSnapshot -> copy of assignments
method seat(guest, table): bool
if table unknown or guest already seated: error
if occupancy(table) >= capacity[table]: return false
assignments[guest] = table
return true
method save(label): PlanSnapshot
snap = new PlanSnapshot(label, size(assignments))
snapshots[snap] = copy(assignments)
return snap
method restore(snap)
if snap not in snapshots: error "not from this plan"
assignments = copy(snapshots[snap])
class AutoSeater
method seatParty(party): table or none
for each table in tables
checkpoint = plan.save(label)
fits = every guest in party: plan.seat(guest, table)
if fits and no keep-apart pair shares a table
return table
plan.restore(checkpoint)
return noneThe code
The same solution in TypeScript, Python and PHP.
type TableId = string;
class PlanSnapshot {
constructor(
readonly label: string,
readonly seatedCount: number,
) {}
}
class SeatingPlan {
private assignments = new Map<string, TableId>();
private readonly snapshots = new WeakMap<PlanSnapshot, Map<string, TableId>>();
constructor(private readonly capacity: Map<TableId, number>) {}
seat(guest: string, table: TableId): boolean {
const max = this.capacity.get(table);
if (max === undefined) throw new Error(`Unknown table ${table}`);
if (this.assignments.has(guest)) throw new Error(`${guest} is already seated`);
if (this.occupancy(table) >= max) return false;
this.assignments.set(guest, table);
return true;
}
tableOf(guest: string): TableId | undefined {
return this.assignments.get(guest);
}
occupancy(table: TableId): number {
let count = 0;
for (const t of this.assignments.values()) if (t === table) count++;
return count;
}
save(label: string): PlanSnapshot {
const snapshot = new PlanSnapshot(label, this.assignments.size);
this.snapshots.set(snapshot, new Map(this.assignments));
return snapshot;
}
restore(snapshot: PlanSnapshot): void {
const state = this.snapshots.get(snapshot);
if (state === undefined) throw new Error("Snapshot was not taken from this plan");
this.assignments = new Map(state);
}
describe(): string {
return [...this.capacity.keys()]
.map((table) => {
const guests = [...this.assignments].filter(([, t]) => t === table).map(([g]) => g);
return `${table}: ${guests.join(", ")}`;
})
.join("\n");
}
}
class AutoSeater {
constructor(
private readonly plan: SeatingPlan,
private readonly tables: TableId[],
private readonly keepApart: Array<[string, string]>,
) {}
seatParty(party: string[]): TableId | null {
for (const table of this.tables) {
const checkpoint = this.plan.save(`${party[0]}'s party at ${table}`);
const fits = party.every((guest) => this.plan.seat(guest, table));
if (fits && !this.violatesKeepApart()) return table;
this.plan.restore(checkpoint);
}
return null;
}
private violatesKeepApart(): boolean {
return this.keepApart.some(([a, b]) => {
const tableA = this.plan.tableOf(a);
return tableA !== undefined && tableA === this.plan.tableOf(b);
});
}
}
const tables: TableId[] = ["T1", "T2", "T3"];
const plan = new SeatingPlan(new Map(tables.map((t): [TableId, number] => [t, 4])));
const seater = new AutoSeater(plan, tables, [["Dana", "Rui"]]);
const parties: string[][] = [
["Ana", "Ben", "Cleo"],
["Dana", "Eli"],
["Rui", "Sam"],
["Uma", "Vic", "Wes", "Xan", "Yara"],
];
for (const party of parties) {
const table = seater.seatParty(party);
console.log(`${party.join(", ")} -> ${table ?? "unseated"}`);
}
console.log(plan.describe());
// Ana, Ben, Cleo -> T1
// Dana, Eli -> T2
// Rui, Sam -> T3
// Uma, Vic, Wes, Xan, Yara -> unseated
// T1: Ana, Ben, Cleo
// T2: Dana, Eli
// T3: Rui, Samfrom __future__ import annotations
import weakref
class PlanSnapshot:
def __init__(self, label: str, seated_count: int) -> None:
self.label = label
self.seated_count = seated_count
class SeatingPlan:
def __init__(self, capacity: dict[str, int]) -> None:
self._capacity = dict(capacity)
self._assignments: dict[str, str] = {}
self._snapshots: weakref.WeakKeyDictionary[PlanSnapshot, dict[str, str]] = (
weakref.WeakKeyDictionary()
)
def seat(self, guest: str, table: str) -> bool:
if table not in self._capacity:
raise ValueError(f"Unknown table {table}")
if guest in self._assignments:
raise ValueError(f"{guest} is already seated")
if self.occupancy(table) >= self._capacity[table]:
return False
self._assignments[guest] = table
return True
def table_of(self, guest: str) -> str | None:
return self._assignments.get(guest)
def occupancy(self, table: str) -> int:
return sum(1 for t in self._assignments.values() if t == table)
def save(self, label: str) -> PlanSnapshot:
snapshot = PlanSnapshot(label, len(self._assignments))
self._snapshots[snapshot] = dict(self._assignments)
return snapshot
def restore(self, snapshot: PlanSnapshot) -> None:
state = self._snapshots.get(snapshot)
if state is None:
raise ValueError("Snapshot was not taken from this plan")
self._assignments = dict(state)
def describe(self) -> str:
lines = []
for table in self._capacity:
guests = [g for g, t in self._assignments.items() if t == table]
lines.append(f"{table}: {', '.join(guests)}")
return "\n".join(lines)
class AutoSeater:
def __init__(
self, plan: SeatingPlan, tables: list[str], keep_apart: list[tuple[str, str]]
) -> None:
self._plan = plan
self._tables = tables
self._keep_apart = keep_apart
def seat_party(self, party: list[str]) -> str | None:
for table in self._tables:
checkpoint = self._plan.save(f"{party[0]}'s party at {table}")
fits = all(self._plan.seat(guest, table) for guest in party)
if fits and not self._violates_keep_apart():
return table
self._plan.restore(checkpoint)
return None
def _violates_keep_apart(self) -> bool:
for a, b in self._keep_apart:
table_a = self._plan.table_of(a)
if table_a is not None and table_a == self._plan.table_of(b):
return True
return False
if __name__ == "__main__":
tables = ["T1", "T2", "T3"]
plan = SeatingPlan({t: 4 for t in tables})
seater = AutoSeater(plan, tables, [("Dana", "Rui")])
parties = [
["Ana", "Ben", "Cleo"],
["Dana", "Eli"],
["Rui", "Sam"],
["Uma", "Vic", "Wes", "Xan", "Yara"],
]
for party in parties:
table = seater.seat_party(party)
print(f"{', '.join(party)} -> {table or 'unseated'}")
print(plan.describe())
# Ana, Ben, Cleo -> T1
# Dana, Eli -> T2
# Rui, Sam -> T3
# Uma, Vic, Wes, Xan, Yara -> unseated
# T1: Ana, Ben, Cleo
# T2: Dana, Eli
# T3: Rui, Sam<?php
declare(strict_types=1);
final class PlanSnapshot
{
public function __construct(
public readonly string $label,
public readonly int $seatedCount,
) {}
}
final class SeatingPlan
{
/** @var array<string, string> */
private array $assignments = [];
private WeakMap $snapshots;
/** @param array<string, int> $capacity */
public function __construct(private readonly array $capacity)
{
$this->snapshots = new WeakMap();
}
public function seat(string $guest, string $table): bool
{
if (!array_key_exists($table, $this->capacity)) {
throw new InvalidArgumentException("Unknown table $table");
}
if (array_key_exists($guest, $this->assignments)) {
throw new LogicException("$guest is already seated");
}
if ($this->occupancy($table) >= $this->capacity[$table]) {
return false;
}
$this->assignments[$guest] = $table;
return true;
}
public function tableOf(string $guest): ?string
{
return $this->assignments[$guest] ?? null;
}
public function occupancy(string $table): int
{
return count(array_keys($this->assignments, $table, true));
}
public function save(string $label): PlanSnapshot
{
$snapshot = new PlanSnapshot($label, count($this->assignments));
$this->snapshots[$snapshot] = $this->assignments; // arrays are copied by value
return $snapshot;
}
public function restore(PlanSnapshot $snapshot): void
{
if (!isset($this->snapshots[$snapshot])) {
throw new LogicException('Snapshot was not taken from this plan');
}
$this->assignments = $this->snapshots[$snapshot];
}
public function describe(): string
{
$lines = [];
foreach (array_keys($this->capacity) as $table) {
$guests = array_keys($this->assignments, $table, true);
$lines[] = $table . ': ' . implode(', ', $guests);
}
return implode(PHP_EOL, $lines);
}
}
final class AutoSeater
{
/**
* @param list<string> $tables
* @param list<array{string, string}> $keepApart
*/
public function __construct(
private readonly SeatingPlan $plan,
private readonly array $tables,
private readonly array $keepApart,
) {}
/** @param list<string> $party */
public function seatParty(array $party): ?string
{
foreach ($this->tables as $table) {
$checkpoint = $this->plan->save("{$party[0]}'s party at $table");
$fits = true;
foreach ($party as $guest) {
if (!$this->plan->seat($guest, $table)) {
$fits = false;
break;
}
}
if ($fits && !$this->violatesKeepApart()) {
return $table;
}
$this->plan->restore($checkpoint);
}
return null;
}
private function violatesKeepApart(): bool
{
foreach ($this->keepApart as [$a, $b]) {
$tableA = $this->plan->tableOf($a);
if ($tableA !== null && $tableA === $this->plan->tableOf($b)) {
return true;
}
}
return false;
}
}
$tables = ['T1', 'T2', 'T3'];
$plan = new SeatingPlan(array_fill_keys($tables, 4));
$seater = new AutoSeater($plan, $tables, [['Dana', 'Rui']]);
$parties = [
['Ana', 'Ben', 'Cleo'],
['Dana', 'Eli'],
['Rui', 'Sam'],
['Uma', 'Vic', 'Wes', 'Xan', 'Yara'],
];
foreach ($parties as $party) {
$table = $seater->seatParty($party);
echo implode(', ', $party) . ' -> ' . ($table ?? 'unseated') . PHP_EOL;
}
echo $plan->describe() . PHP_EOL;
// Ana, Ben, Cleo -> T1
// Dana, Eli -> T2
// Rui, Sam -> T3
// Uma, Vic, Wes, Xan, Yara -> unseated
// T1: Ana, Ben, Cleo
// T2: Dana, Eli
// T3: Rui, SamWhen to use it
Situations where it pays off.
You need to roll an object back after a tentative change: a search with backtracking, a what-if preview, or a multi-step edit the user can cancel.
A snapshot taken before the attempt makes rollback a single call that restores everything, including fields added later. You don't have to write and maintain reverse operations for each change.
Exposing the object's fields through getters and setters would let callers break its invariants.
The memento carries the state without publishing it. Callers can only restore states the object itself produced, so they cannot assemble an invalid one.
Some code needs to manage a history of states (checkpoints, undo stacks, autosave slots) but has no business knowing what those states contain.
The caretaker can store, label, order and discard snapshots against a small public surface, while the originator stays free to change its internal representation.
The state is small enough to copy, or can be copied incrementally, at the frequency you need.
Memento trades memory and copy time for simplicity. It suits a plan of a few hundred assignments. A multi-gigabyte model saved every keystroke needs diffs or a different approach.
How to implement it
Steps to introduce it in existing code.
Decide which class owns the state to be rolled back. That class becomes the originator, and only it should know how to capture and rebuild that state.
Create the memento class with immutable, non-sensitive metadata only, such as a label, a timestamp or a count. Keep the real state out of its public API.
Choose how the originator reaches the hidden state: a nested or package-private class, name-mangled fields, or a private weak map keyed by snapshot as in this guide. Pick whichever fits your language's visibility rules.
Add
save()to the originator. It must deep-copy every mutable piece of state so that later changes cannot leak into the snapshot.Add
restore(snapshot). Validate that the snapshot came from this object, then rebuild the state from a copy so the same snapshot can be restored more than once.Make the caretaker call
save()before risky work andrestore()on failure. Decide how long it keeps snapshots, and drop them as soon as they are no longer needed so their memory can be reclaimed.
Pros and cons
What you gain and what you pay.
Pros
- Rollback covers the whole state, including fields added later, without writing a reverse operation for every mutation.
- The originator keeps its invariants and its internal representation private. Caretakers depend only on an opaque token.
- Caretaker logic such as backtracking, undo stacks or autosave slots stays simple and does not change when the originator's fields change.
- Snapshots are immutable values that are easy to keep in lists, label for debugging and discard.
Cons
- Each snapshot copies state. Frequent saves of large objects cost memory and time, which can be O(n) per checkpoint for n assignments.
- Enforcing true opacity is awkward in languages without friend or nested-class access, and you end up with conventions or a private registry.
- Caretakers that hold snapshots too long keep old state alive, which is easy to miss in long-running sessions.
- Snapshots go stale when the originator's format changes. Persisted mementos need versioning or migration.
Relations with other guides
Patterns it's often confused or combined with.
- Command Pattern: Turn Requests into Objects You Can Queue and Undo
Commands often save a memento before executing so
undo()can restore it. This is useful when writing an exact inverse operation is hard. - Prototype Pattern: Create Objects by Cloning a Configured Instance
When the whole object is cheap to clone and has no hidden links, a Prototype-style clone can act as a simpler memento. Memento adds control over what is exposed and restored.
- Iterator Pattern: Walk Any Collection Without Knowing Its Shape
An iterator can return a memento of its position so a traversal can be paused and resumed later without revealing the cursor internals.
- State Pattern: Explicit State Machines Without the Switch Statements
Both deal with an object's state, but State changes behaviour based on it, while Memento records and brings back past values of it.
- Event Sourcing: Store What Happened, Derive What Is
Event-sourced systems often store periodic snapshots, which are mementos of an aggregate, so they don't have to replay every event from the start.
- Saga: Multi-Service Transactions with Compensations
A saga rolls back with compensating actions across services. A memento rolls back a single object in memory by restoring a captured state.
Common questions
Short answers to the usual doubts.
What is the difference between the narrow and wide interface of a memento?
The narrow interface is what the caretaker sees: here, label and seatedCount, which are enough to store, log and pass the snapshot back. The wide interface is full access to the captured state, and only the originator should have it. Languages with nested classes or friend access can enforce this directly. In TypeScript, Python and PHP, a private registry keyed by snapshot, like the weak map in this guide, gives the same separation.
Why not just give SeatingPlan a clone() method and keep copies of the whole plan?
You can, and for small self-contained objects that is a reasonable shortcut. The catch is that a clone is a fully working plan, so the caretaker can call seat() on it, read every assignment and pass it anywhere. A memento can only be handed back to its originator. It also lets the originator choose what to capture, for example the assignments but not a shared capacity map that never changes.
How expensive is each checkpoint in this example?
save() copies the assignment map, which is O(n) time and memory for n seated guests, and restore() copies it again. For a gala with 140 guests that is trivial even across hundreds of attempts. For much larger state you would store diffs, use persistent (structurally shared) data structures, or switch to command-based undo that records only the change.
Why does restore() copy the stored state instead of reusing it directly?
If the plan adopted the stored map as its live state, the next seat() call would mutate the snapshot too, and restoring the same checkpoint a second time would bring back the wrong state. Copying on both save and restore keeps every snapshot immutable, so it can be restored any number of times.
How does Memento relate to undo in a Command-based design?
They solve undo from two directions. A command can reverse itself by applying an inverse operation, which is cheap but must be written correctly for every command. Or it can save a memento before executing and restore it on undo, which is simpler and always complete but costs a copy of the state. Many systems mix the two, using inverse operations for common cheap edits and mementos for complex ones.
When would you not use Memento?
Skip it when the state is huge and changes often, when the state lives outside the process (a database row is better rolled back with a transaction), or when the object has no internals worth hiding, in which case a plain value copy is clearer. Also be careful when the state holds handles such as open connections or file locks, because copying those does not restore them.