Notes
The problem
Here is the naive way. The planner screen copies the stops, the budget and the hotel into local variables before each change, and writes them back on undo. To do that, those fields must be public, or have getters and setters that exist only for undo. Every new field means fixing every screen. And any class can now put the itinerary into a state that its own rules would never allow.
// fields made public just for undo List<String> oldStops = trip.stops; int oldBudget = trip.budget; String oldHotel = trip.hotel; ... trip.stops = oldStops; trip.budget = oldBudget; // add a field: fix every screen
The hidden bug
There is also a quieter bug. The screen saves the stops list itself, not a copy. Then the user adds Udaipur. The backup now contains Udaipur too, because it is the same list object. Undo restores nothing. Only the itinerary knows which of its fields are mutable and need a real copy, which is a strong hint that the itinerary should make its own backups.
trip.stops.add("Jaipur");
List<String> backup = trip.stops;
trip.stops.add("Udaipur");
backup -> [Jaipur, Udaipur]
// same list object, not a copy The idea
The idea in one sentence: let an object capture its own state in a snapshot, so it can be restored later, without anyone else seeing inside. The snapshot is the memento. Outsiders can keep it, put it on a stack, even throw it away, but they cannot read it or change it. Only the object that made it can open it again. The state never leaves the class in a readable form.
- the object saves its own
- state into a snapshot
- outsiders store the snapshot
- but cannot read or change it
- later the same object
- restores itself from it
- state never leaves the class
- in readable form
Participants
Three roles, with our names. The itinerary is the originator: it owns the state, creates snapshots and restores from them. Itinerary snapshot is the memento: an opaque token. Undo history is the caretaker: it decides when snapshots are kept and in what order, using an undo stack and a redo stack, but it never looks inside one. The planner screen is the client that calls edit, undo and redo.
The memento in Java
How do we make the memento opaque in Java? Outside, there is a public interface, itinerary snapshot, with only a label for display. Inside the itinerary, a private record called State implements it and holds the real data. Because the record is private, no other class can even name its type. Save copies the stops with list copy of, which makes an unmodifiable copy, so later edits cannot reach the snapshot.
interface ItinerarySnapshot {
String label(); }
final class Itinerary {
private record State(Itinerary owner,
List<String> stops, int budget,
String hotel, String label)
implements ItinerarySnapshot { }
ItinerarySnapshot save(String label) {
return new State(this,
List.copyOf(stops), budget,
hotel, label); } Restoring
Restore takes the opaque snapshot and uses pattern matching for instance of to turn it back into the private State record. It also checks the owner, so a snapshot of someone else's trip cannot be loaded into this one. Then it copies the values back into its own fields. The itinerary can also re-check its own rules here, which no outside class could be trusted to do.
void restore(ItinerarySnapshot snap) {
if (!(snap instanceof State s)
|| s.owner() != this)
throw new IllegalArgumentException(
"not a snapshot of this trip");
stops.clear();
stops.addAll(s.stops());
budget = s.budget();
hotel = s.hotel();
} The caretaker
The caretaker is undo history. Before every change, it pushes a snapshot onto the undo stack. If the stack grows past its limit, the oldest snapshot is dropped. Any new edit clears the redo stack, because the old future no longer makes sense. To undo, it pops the latest snapshot, saves the current state onto the redo stack, and asks the itinerary to restore. Redo is the mirror image.
Deque<ItinerarySnapshot> undo, redo;
void beforeChange(ItinerarySnapshot s) {
undo.push(s);
if (undo.size() > limit)
undo.removeLast(); // drop oldest
redo.clear(); }
undo: pop from undo, push the
current state onto redo, restore One run
Follow one change. The user raises the budget from thirty thousand to forty five thousand. First the screen asks the itinerary for a snapshot labelled set budget, and hands it to the history. Then it makes the change. When the user presses undo, the history pops that snapshot, keeps the current state for redo, and the itinerary restores itself. The budget is thirty thousand again, and the screen never touched a field.
Memory cost
Mementos cost memory. Each one is a full copy of the state, so a large object with a deep history adds up quickly. Cap the history, for example at the last fifty steps. Take a snapshot per meaningful action, not per key press. Immutable parts, like strings or an unmodifiable list that has not changed, can be shared between snapshots without copying. For very large state, store only the difference, or move old history to disk.
- cap the history: last 50
- snapshot per meaningful step,
- not per key press
- immutable parts can be shared
- between snapshots, no copy
- big state: store a diff
- instead of a full copy
- old history: compress or
- move to disk
Versus Command
There are two classic ways to build undo. Memento stores what the state was. It is simple and always correct, but it costs memory for every step. Command stores the action and knows how to reverse it, like remove the city that was just added. That is small, but every action needs a correct inverse, which is hard for things like sorting. Many editors mix them: a command holds a memento for the hard cases.
- Memento: store what it was
- simple, always correct
- costs memory per step
- Command: store the action
- and its inverse
- small, but every action
- needs a correct undo()
- mix: a command keeps a memento
When to use it
Use a memento when you need undo and redo, checkpoints in a game or a wizard, or a way to roll back an object when a multi step operation fails halfway, and the state should stay private. Skip it when the state is huge and each change is tiny, where storing commands is cheaper. And if your object is already immutable, you do not need a memento at all: just keep references to the old versions.
- use it when:
- you need undo or redo
- you need checkpoints to
- roll back a failed step
- state must stay private
- skip it when:
- state is huge and changes
- are small: store commands
- the object is already
- immutable: keep old versions
In Java
The JDK has no class called memento, but JDBC shows the same idea. Inside a transaction, connection dot set savepoint returns a savepoint object. If a later step fails, connection dot rollback with that savepoint undoes the work done after it. You hold an opaque handle, and only the database knows what it really contains. Game save files and editor undo stacks follow the same shape.
Savepoint sp = conn.setSavepoint();
try {
applyDiscounts(conn);
} catch (SQLException e) {
conn.rollback(sp); // back to sp
}
// the Savepoint is an opaque handle;
// the database keeps the real state In LLD interviews
In interviews, listen for the words undo, redo, draft or checkpoint. A text editor or drawing tool needs undo and redo stacks. A chess game may let players take back a move. A form wizard saves a draft and goes back a step. A game keeps checkpoints. When you propose it, name the three roles, say the memento is opaque, and mention a history limit before the interviewer asks about memory.
- text or document editor:
- undo and redo stacks
- drawing or design tool
- chess: take back a move
- form wizard: save a draft,
- go back a step
- game: checkpoints
- shopping cart: restore after
- a failed checkout
Common mistakes
Common mistakes. Saving a reference to a mutable list instead of a copy, so the snapshot changes along with the object. Giving the memento public setters, so anyone can edit history. A caretaker that reads inside snapshots, which brings back the coupling we removed. No limit on history, so memory grows forever. And forgetting to clear the redo stack after a new edit, which lets redo jump to a state that no longer fits.
- saving a reference to a
- mutable list: not a copy
- memento with public setters
- caretaker reading inside
- the snapshot
- no history limit: memory
- grows forever
- new edit keeps the old
- redo stack