These are the notes for Low-Level Design (LLD) episode 42, the ninth behavioural pattern (patterns about how objects share work and talk to each other). A memento is a sealed snapshot of an object's private state, so the object can be put back the way it was, for undo, checkpoints or rollback, without making its fields public. We start with a video game checkpoint, watch a billing app's undo do nothing at all, and invent the pattern as the fix. Then we test the seal with the compiler, fall into the shallow-copy trap, measure the memory cost, and compare Memento with Command for undo. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.
1. The real-life idea: a checkpoint in a video game
| In a video game | In code |
|---|---|
| The game: knows your level, health, coins | The originator: the object whose state we save |
| The save file: you can't read or edit it | The memento: a sealed snapshot of that state ("memento" = a small thing kept to remember a moment) |
| The save-slot menu: keeps saves, never opens them | The caretaker: stores mementos, never looks inside |
| "Load checkpoint": back to exactly that moment | Restore: the originator rebuilds itself from the memento |
2. The problem: an undo that does nothing
An Order at Asha's cafe has a private list of items and a discount, which by the cafe's rule is at most 20%. That rule is an invariant: something that must always be true about the object. The obvious undo: keep the order in a variable before changing it.
import java.util.*;
class Order {
private final List<String> items = new ArrayList<>();
private int discount = 0; // percent, max 20
void add(String item) { items.add(item); }
void setDiscount(int d) { if (d >= 0 && d <= 20) discount = d; } // rule: max 20%
public String toString() { return items + ", " + discount + "% off"; }
}
public class Main {
public static void main(String[] args) {
Order order = new Order();
order.add("Thali"); order.add("Chai");
Order saved = order; // "save" before changing
order.add("Biryani"); order.setDiscount(10);
System.out.println("now: " + order);
order = saved; // "undo"
System.out.println("undone: " + order);
}
}
Output (real):
now: [Thali, Chai, Biryani], 10% off
undone: [Thali, Chai, Biryani], 10% off
"Undone" prints exactly the same order. Order saved = order; copies a reference (episode 2): a second name for the same object. Every change to order was a change to saved.
Why it failed
- A reference is not a copy: nothing was saved.
- Copying the fields from outside the class is impossible: they're
private. - Making them
publicwould let any code set 90% off and break the invariant. That breaks encapsulation (episode 6): keeping an object's data private so only its own methods can change it. - Like the game: the object must write its own save file, which others keep but can't open.
3. The fix: originator, memento, caretaker
import java.util.*;
class Order { // the originator
private List<String> items = new ArrayList<>(); private int discount = 0;
void add(String item) { items.add(item); }
void setDiscount(int d) { if (d >= 0 && d <= 20) discount = d; } // rule: max 20%
public String toString() { return items + ", " + discount + "% off"; }
static final class Memento { // the snapshot: opaque
private final List<String> items; private final int discount;
private Memento(List<String> i, int d) { items = i; discount = d; }
}
Memento save() { return new Memento(List.copyOf(items), discount); } // a real copy
void restore(Memento m) { items = new ArrayList<>(m.items); discount = m.discount; }
}
class History { // the caretaker
private final Deque<Order.Memento> stack = new ArrayDeque<>();
void push(Order.Memento m) { stack.push(m); } Order.Memento pop() { return stack.pop(); }
}
public class Main {
public static void main(String[] args) {
Order order = new Order(); History h = new History();
order.add("Thali"); order.add("Chai");
h.push(order.save()); order.add("Biryani");
h.push(order.save()); order.setDiscount(10);
System.out.println("now: " + order);
order.restore(h.pop()); System.out.println("undo 1: " + order);
order.restore(h.pop()); System.out.println("undo 2: " + order);
}
}
Output (real):
now: [Thali, Chai, Biryani], 10% off
undo 1: [Thali, Chai, Biryani], 0% off
undo 2: [Thali, Chai], 0% off
Orderis the originator.save()makes aMementowith a real copy of the items (List.copyOf) and the discount;restore(m)rebuilds the fields from it.Order.Mementois a nested class: a class written inside another class. Its fields and even its constructor areprivate. In Java, the enclosing class can use a nested class's private members, so onlyOrdercan create and read mementos.Historyis the caretaker: a stack (ArrayDeque, episode 4).pushbefore each change,popto undo. It never looks inside.- Undo works one step at a time, and
Order's fields are still private.
4. It has a name: the Memento pattern
Order (originator) - - creates, reads - -▶ Order.Memento (sealed) ◀── keeps, can't open ── History (caretaker)
- items, - discount - items (a copy) - stack: Deque<Memento>
+ save(), + restore(m) - discount + push(m), + pop()
▲ ▲
└────────────────────────────── Main (client): save before a change, restore on undo ──────────┘
| Role | In our code | SourceMaking's description |
|---|---|---|
| Originator | Order, Editor |
"the object that knows how to save itself" |
| Caretaker | History |
"the object that knows why and when the Originator needs to save and restore itself" |
| Memento | Order.Memento, Editor.Snapshot |
"the lock box that is written and read by the Originator, and shepherded by the Caretaker" |
The classic intent: "Without violating encapsulation, capture and externalize an object's internal state so that the object can be returned to this state later." Externalize = hand it to someone outside to keep.
5. Keeping the snapshot sealed
A "harmless" helper in the caretaker tries to peek inside:
import java.util.*;
class Order { // the originator
private List<String> items = new ArrayList<>(); private int discount = 0;
void add(String item) { items.add(item); }
void setDiscount(int d) { if (d >= 0 && d <= 20) discount = d; } // rule: max 20%
public String toString() { return items + ", " + discount + "% off"; }
static final class Memento { // the snapshot: opaque
private final List<String> items; private final int discount;
private Memento(List<String> i, int d) { items = i; discount = d; }
}
Memento save() { return new Memento(List.copyOf(items), discount); } // a real copy
void restore(Memento m) { items = new ArrayList<>(m.items); discount = m.discount; }
}
class History { // the caretaker
private final Deque<Order.Memento> stack = new ArrayDeque<>();
void push(Order.Memento m) { stack.push(m); } Order.Memento pop() { return stack.pop(); }
int lastDiscount() { return stack.peek().discount; } // just a peek...
}
public class Main {
public static void main(String[] args) {
Order order = new Order(); History h = new History();
order.add("Thali"); order.add("Chai");
h.push(order.save()); order.add("Biryani");
h.push(order.save()); order.setDiscount(10);
System.out.println("now: " + order);
order.restore(h.pop()); System.out.println("undo 1: " + order);
order.restore(h.pop()); System.out.println("undo 2: " + order);
}
}
Output (real):
Main.java:17: error: discount has private access in Memento
int lastDiscount() { return stack.peek().discount; } // just a peek...
^
1 error
The compiler itself keeps the caretaker out. This is the encapsulation of saved state: if the caretaker could edit a snapshot, it could put 90% off into one, and restore would quietly load a broken order. Because only Order reads mementos, the 20% rule can never be bypassed.
(A record with private components still gets public accessor methods, so a record used as a memento is readable by anyone who holds it. That's fine when the state isn't secret, as in the editor in section 7; for real sealing, use a class with private fields nested in the originator.)
6. The trap: a snapshot that isn't a copy
Same program, but save() passes the live list into the memento:
import java.util.*;
class Order { // the originator
private List<String> items = new ArrayList<>(); private int discount = 0;
void add(String item) { items.add(item); }
void setDiscount(int d) { if (d >= 0 && d <= 20) discount = d; } // rule: max 20%
public String toString() { return items + ", " + discount + "% off"; }
static final class Memento { // the snapshot: opaque
private final List<String> items; private final int discount;
private Memento(List<String> i, int d) { items = i; discount = d; }
}
Memento save() { return new Memento(items, discount); } // no copy...
void restore(Memento m) { items = new ArrayList<>(m.items); discount = m.discount; }
}
class History { // the caretaker
private final Deque<Order.Memento> stack = new ArrayDeque<>();
void push(Order.Memento m) { stack.push(m); } Order.Memento pop() { return stack.pop(); }
}
public class Main {
public static void main(String[] args) {
Order order = new Order(); History h = new History();
order.add("Thali"); order.add("Chai");
h.push(order.save()); order.add("Biryani");
h.push(order.save()); order.setDiscount(10);
System.out.println("now: " + order);
order.restore(h.pop()); System.out.println("undo 1: " + order);
order.restore(h.pop()); System.out.println("undo 2: " + order);
}
}
Output (real):
now: [Thali, Chai, Biryani], 10% off
undo 1: [Thali, Chai, Biryani], 0% off
undo 2: [Thali, Chai, Biryani], 0% off
The second undo still shows Biryani. The memento kept a reference to the order's live list, so when Biryani was added, it was added "inside" the old snapshot too. That's a shallow copy: copying the outer object but sharing the things inside it.
Rule: a snapshot must copy everything that can change later. List.copyOf makes an unmodifiable copy (nobody can change it afterwards). The String items are immutable (they can never change), so sharing them is safe. If the items were mutable objects, you would copy them too: a deep copy.
7. The memory cost of snapshots
import java.util.*;
class Editor { // the originator
private String text = "";
void type(String s) { text += s; } String text() { return text; }
record Snapshot(String text) { } // the memento
Snapshot save() { return new Snapshot(text); } void restore(Snapshot s) { text = s.text(); }
}
class History { // a bounded caretaker
private final Deque<Editor.Snapshot> stack = new ArrayDeque<>();
void push(Editor.Snapshot s) { stack.push(s); if (stack.size() > 3) stack.removeLast(); }
Editor.Snapshot pop() { return stack.poll(); } // null when empty
int charsKept() { return stack.stream().mapToInt(s -> s.text().length()).sum(); }
}
public class Main {
public static void main(String[] args) {
Editor e = new Editor(); History h = new History();
for (String w : List.of("Menu: ", "Poha ", "Upma ", "Idli ", "Dosa ")) {
h.push(e.save()); e.type(w); // save, then change
}
System.out.println("text: " + e.text() + "| chars kept: " + h.charsKept());
for (int i = 1; i <= 4; i++) {
Editor.Snapshot s = h.pop();
if (s == null) { System.out.println("undo " + i + ": nothing left"); continue; }
e.restore(s); System.out.println("undo " + i + ": " + e.text());
}
}
}
Output (real):
text: Menu: Poha Upma Idli Dosa | chars kept: 48
undo 1: Menu: Poha Upma Idli
undo 2: Menu: Poha Upma
undo 3: Menu: Poha
undo 4: nothing left
Each Snapshot (a record, the memento) holds the whole text, so snapshots grow as the text grows. A 1 MB document with 1,000 saved edits would keep about 1,000 MB. So this History is bounded: it keeps the last 3 snapshots, and push forgets the oldest with removeLast(). Three undos work; the fourth has nothing left. That's the trade: a fixed memory budget for a limited undo history.
Ways to save memory:
- Bound the history (last N snapshots).
- Store only what changed: a diff (or delta).
- Save snapshots less often (every 10 edits, or on a timer).
- For huge state with easily reversible actions, use Command undo instead.
8. Memento vs Command for undo
| Command (episode 36) | Memento | |
|---|---|---|
| Stores | the action (and how to reverse it) | the state before a change |
| Undo means | call command.undo() |
originator.restore(memento) |
| Memory | small: only the change | grows with the object's size |
| Code | an undo() for every command; one bug corrupts state |
one save/restore, generic and exact |
| Watch out for | actions that can't be reversed (sending an email) | shallow copies, memory |
They combine well: each command keeps a memento of the state it changed, and its undo() restores it.
9. When to use it (and when not)
| Use it for | Skip it when |
|---|---|
| Undo and redo (editors, drawing apps, billing screens) | The state is tiny and already public |
| Checkpoints (games, long-running jobs, multi-step wizards) | A command can simply reverse itself |
| Rollback: try a risky change, restore if it fails | Snapshots would be huge and frequent |
| Keeping private state private while someone else stores it |
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
Order saved = order; |
No error: undo does nothing | A reference, not a copy | order.save() returns a snapshot |
| Caretaker reads the memento | error: discount has private access in Memento |
The snapshot is sealed | Only the originator reads it |
| Memento keeps the live list | No error: Biryani still there after undo | Shallow copy changes later | List.copyOf / deep copy |
| Making fields public to snapshot them | No error: anyone can set 90% off | Encapsulation broken | Nested private memento |
| Unbounded snapshots of big data | java.lang.OutOfMemoryError in a long session |
Every save keeps everything | Bound history, diffs, or commands |
| Forgetting to save before a change | Undo jumps back two steps | No snapshot for that change | Save in one place, right before each change |
Mini project: undo and redo
Redo needs a second stack: undo moves the current state onto the redo stack; any new change clears it.
import java.util.*;
class Editor { // the originator
private String text = "";
void type(String s) { text += s; }
String text() { return text; }
static final class Memento { // sealed
private final String text;
private Memento(String t) { text = t; }
}
Memento save() { return new Memento(text); }
void restore(Memento m) { text = m.text; }
}
class History { // the caretaker
private final Deque<Editor.Memento> undo = new ArrayDeque<>(), redo = new ArrayDeque<>();
private final Editor e;
History(Editor e) { this.e = e; }
void change(String s) { undo.push(e.save()); redo.clear(); e.type(s); }
void undo() { if (undo.isEmpty()) return; redo.push(e.save()); e.restore(undo.pop()); }
void redo() { if (redo.isEmpty()) return; undo.push(e.save()); e.restore(redo.pop()); }
}
public class Main {
public static void main(String[] args) {
Editor e = new Editor(); History h = new History(e);
h.change("Poha "); h.change("Upma "); h.change("Idli ");
System.out.println("typed: " + e.text());
h.undo(); h.undo(); System.out.println("undo 2: " + e.text());
h.redo(); System.out.println("redo 1: " + e.text());
h.change("Dosa "); System.out.println("new: " + e.text());
h.redo(); System.out.println("redo: " + e.text() + "(nothing to redo)");
}
}
Output (real):
typed: Poha Upma Idli
undo 2: Poha
redo 1: Poha Upma
new: Poha Upma Dosa
redo: Poha Upma Dosa (nothing to redo)
Practice
1. Save a game: a Game with level, health and coins; save at a checkpoint, lose health and coins, then load the checkpoint.
Answer
import java.util.*;
class Game { // the originator
private int level = 1, health = 100, coins = 0;
void play(int dLevel, int dHealth, int dCoins) { level += dLevel; health += dHealth; coins += dCoins; }
public String toString() { return "level " + level + ", health " + health + ", coins " + coins; }
static final class Save { // the memento
private final int level, health, coins;
private Save(int l, int h, int c) { level = l; health = h; coins = c; }
}
Save save() { return new Save(level, health, coins); }
void load(Save s) { level = s.level; health = s.health; coins = s.coins; }
}
public class Main {
public static void main(String[] args) {
Game g = new Game();
g.play(2, -10, 50); Game.Save checkpoint = g.save(); // the caretaker: a variable
System.out.println("checkpoint: " + g);
g.play(0, -90, -50); System.out.println("fell: " + g);
g.load(checkpoint); System.out.println("loaded: " + g);
}
}
Output (real):
checkpoint: level 3, health 90, coins 50
fell: level 3, health 0, coins 0
loaded: level 3, health 90, coins 50
2. Suppose a memento stores a list of mutable Item objects with List.copyOf. Is that enough? Show what goes wrong and fix it with a deep copy.
Answer
List.copyOf copies the list, but both lists point at the same Item objects, so changing an item's quantity changes the snapshot too. A deep copy copies each item:
import java.util.*;
class Item {
final String name; int qty;
Item(String name, int qty) { this.name = name; this.qty = qty; }
Item copy() { return new Item(name, qty); }
public String toString() { return name + " x" + qty; }
}
public class Main {
public static void main(String[] args) {
List<Item> order = new ArrayList<>(List.of(new Item("Chai", 1)));
List<Item> shallow = List.copyOf(order); // copies the list only
List<Item> deep = order.stream().map(Item::copy).toList(); // copies every item
order.get(0).qty = 5; // change after the snapshot
System.out.println("order: " + order);
System.out.println("shallow: " + shallow);
System.out.println("deep: " + deep);
}
}
Output (real):
order: [Chai x5]
shallow: [Chai x5]
deep: [Chai x1]
3. Make the Order history keep only the last 10 snapshots. Which ArrayDeque method forgets the oldest one when you push new ones on the front?
Answer
push adds at the front, so the oldest snapshot is at the back: after stack.push(m), if (stack.size() > 10) stack.removeLast();
4. Why is Order saved = order; not a snapshot, while order.save() is?
Answer
The assignment copies a reference: two names for one object, so later changes show through both. save() creates a new object holding copies of the state at that moment, which later changes can't touch.
Quick quiz
List<String> items =
new ArrayList<>(List.of("Chai"));
List<String> snap = items; // "save"
items.add("Poha");
items = snap; // "undo"
System.out.println(items);
What is printed? (a) [Chai] (b) [Chai, Poha] (c) [] (d) Compile error
Answer
(b) [Chai, Poha]. snap = items copies the reference, not the list, so there was only ever one list. A real snapshot needs List.copyOf(items).
Interview questions
- What is the Memento pattern? A behavioural pattern that captures an object's internal state in a snapshot object, without breaking encapsulation, so the object can be restored to that state later.
- Participants? Originator (creates and restores from mementos), memento (the snapshot), caretaker (stores mementos, never inspects them).
- How do you keep a memento opaque in Java? A
staticnested class inside the originator with private fields and a private constructor; only the originator can use them. - Shallow vs deep snapshot? Shallow shares mutable parts with the live object, so the snapshot changes later; deep copies everything that can change.
- Memento vs Command for undo? Command stores actions and their inverses (light, but every command needs a correct undo); Memento stores state (simple and exact, but memory-heavy). Often combined.
- How do you implement redo? A second stack: undo pushes the current state to redo; any new change clears redo.
- Memory concerns? Snapshots of large objects are expensive; bound the history, store diffs, snapshot less often.
- Real uses? Editor undo/redo, game checkpoints, transaction rollback, form "reset to saved", wizard back buttons.
- Who decides when to save? The caretaker (or client): it knows why and when; the originator knows how.
- Can a
recordbe a memento? Yes, and it's convenient, but its accessors are public, so it isn't sealed; use it when the state needn't be hidden.
Glossary
| Term | Meaning, with an example |
|---|---|
| Behavioural pattern | A design pattern about how objects share work and talk to each other |
| Memento pattern | Capture an object's state in a sealed snapshot, without breaking encapsulation, to restore it later |
| Originator | The object whose state is saved; it creates mementos and restores from them. Order, the game |
| Memento | The sealed snapshot of the originator's state. The save file, Order.Memento |
| Caretaker | Keeps mementos and decides when to save/restore, but never looks inside. History, the save slots |
| Snapshot | A copy of an object's state at one moment |
| Restore | Put an object back to the state stored in a memento |
| Undo with snapshots | Save a memento before each change; undo = restore the latest one |
| Reference | A value that points to an object; copying it gives a second name for the same object (episode 2) |
| Invariant | Something that must always be true about an object. "Discount is at most 20%" |
| Encapsulation | Keeping an object's data private so only its own methods can change it (episode 6) |
| Encapsulation of saved state | Only the originator can read or change what's inside a memento |
| Externalize | Hand state to an object outside the originator to keep |
| Nested class | A class written inside another class; the outer class can use its private members |
| Shallow copy | Copies the outer object but shares the objects inside it |
| Deep copy | Copies the object and everything inside it that can change |
| Unmodifiable copy | A copy nobody can change. List.copyOf(items) |
| Immutable | Can never change after creation. String |
| Stack | Last in, first out: push adds on top, pop takes the top. An ArrayDeque |
| Bounded history | Keep only the last N snapshots to cap memory |
| Diff / delta | Only the part that changed between two states |
| Memory cost of snapshots | Full snapshots × object size × number of saves |
| Command pattern | Turn an action into an object with execute() and undo() (episode 36) |
record |
A compact Java class for plain data, with public accessor methods |
Summary
saved = ordercopies a reference, so "undo" does nothing.- Memento pattern: the originator saves itself into a sealed memento; the caretaker keeps mementos without looking inside; undo = restore.
- A nested class with private members makes the snapshot sealed: the compiler stops the caretaker (
has private access). - Copy everything that can change: a shallow snapshot changes after it's taken.
- Snapshots cost memory: bound the history, store diffs, or use Command undo.
Next episode: The Visitor pattern: add a new operation to a whole family of classes without editing any of them.