LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 42 OF 48

Memento Pattern in Java: Undo and Snapshots Without Leaking State

The Memento pattern in Java with a trip planner: the itinerary saves its state into an opaque snapshot, a caretaker keeps undo and redo stacks without reading inside, and the itinerary restores itself. Covers deep copies, a private record as the memento, history limits and memory cost, Memento versus Command for undo, and where it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 173 lines, with a small main() demo. Save it as TripUndoDemo.java, then run javac TripUndoDemo.java && java TripUndoDemo.

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * Memento: the itinerary saves and restores its own state; the undo history
 * stores snapshots without being able to read them.
 */
public class TripUndoDemo {

    public static void main(String[] args) {
        // BEFORE: a "backup" that shares the same mutable list.
        List<String> stops = new ArrayList<>();
        stops.add("Jaipur");
        List<String> backup = stops;           // a reference, not a copy
        stops.add("Udaipur");
        System.out.println("Before: backup should be [Jaipur] but is " + backup);
        System.out.println();

        // AFTER: originator + memento + caretaker.
        Itinerary trip = new Itinerary(30000);
        PlannerScreen screen = new PlannerScreen(trip, new UndoHistory(3));
        screen.edit("add Jaipur", () -> trip.addStop("Jaipur"));
        screen.edit("add Udaipur", () -> trip.addStop("Udaipur"));
        screen.edit("set budget", () -> trip.setBudget(45000));
        screen.edit("book hotel", () -> trip.bookHotel("Lake View"));
        screen.undo();
        screen.undo();
        screen.redo();
        screen.edit("add Jodhpur", () -> trip.addStop("Jodhpur"));   // clears redo
        screen.redo();
        screen.undo();
        screen.undo();
        screen.undo();
        screen.undo();   // limit is 3, the oldest snapshot was dropped

        // A snapshot from another itinerary is refused.
        Itinerary other = new Itinerary(10000);
        try {
            trip.restore(other.save("someone else"));
        } catch (IllegalArgumentException e) {
            System.out.println("Refused: " + e.getMessage());
        }
    }
}

/** Memento as seen from outside: an opaque token with a label for display. */
interface ItinerarySnapshot {
    String label();
}

/** Originator: owns the state, creates snapshots and restores from them. */
final class Itinerary {
    private final List<String> stops = new ArrayList<>();
    private int budget;
    private String hotel = "none";

    Itinerary(int budget) {
        this.budget = budget;
    }

    void addStop(String city) {
        stops.add(city);
    }

    void setBudget(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("budget must be positive");
        }
        budget = amount;
    }

    void bookHotel(String name) {
        hotel = name;
    }

    /** The real memento: private, so no other class can name it or read it. */
    private record State(Itinerary owner, List<String> stops, int budget, String hotel, String label)
            implements ItinerarySnapshot {
        @Override
        public String toString() {
            return "snapshot(" + label + ")";   // never print the private data
        }
    }

    ItinerarySnapshot save(String label) {
        return new State(this, List.copyOf(stops), budget, hotel, label);   // copy mutable parts
    }

    void restore(ItinerarySnapshot snapshot) {
        if (!(snapshot instanceof State s) || s.owner() != this) {
            throw new IllegalArgumentException("not a snapshot of this itinerary");
        }
        stops.clear();
        stops.addAll(s.stops());
        budget = s.budget();
        hotel = s.hotel();
    }

    @Override
    public String toString() {
        return "stops=" + stops + ", budget=" + budget + ", hotel=" + hotel;
    }
}

/** Caretaker: keeps snapshots in order, never looks inside them. */
final class UndoHistory {
    private final Deque<ItinerarySnapshot> undo = new ArrayDeque<>();
    private final Deque<ItinerarySnapshot> redo = new ArrayDeque<>();
    private final int limit;

    UndoHistory(int limit) {
        this.limit = limit;
    }

    void beforeChange(ItinerarySnapshot snapshot) {
        undo.push(snapshot);
        if (undo.size() > limit) {
            undo.removeLast();                 // drop the oldest to bound memory
        }
        redo.clear();                          // a new edit makes the old future invalid
    }

    String undo(Itinerary trip) {
        if (undo.isEmpty()) {
            return "nothing to undo";
        }
        ItinerarySnapshot s = undo.pop();
        redo.push(trip.save(s.label()));
        trip.restore(s);
        return "undo " + s.label();
    }

    String redo(Itinerary trip) {
        if (redo.isEmpty()) {
            return "nothing to redo";
        }
        ItinerarySnapshot s = redo.pop();
        undo.push(trip.save(s.label()));
        trip.restore(s);
        return "redo " + s.label();
    }
}

/** Client: saves before every change and forwards undo and redo. */
final class PlannerScreen {
    private final Itinerary trip;
    private final UndoHistory history;

    PlannerScreen(Itinerary trip, UndoHistory history) {
        this.trip = trip;
        this.history = history;
    }

    void edit(String what, Runnable change) {
        history.beforeChange(trip.save(what));
        change.run();
        System.out.println(pad(what) + trip);
    }

    void undo() {
        System.out.println(pad(history.undo(trip)) + trip);
    }

    void redo() {
        System.out.println(pad(history.redo(trip)) + trip);
    }

    private static String pad(String s) {
        return String.format("%-18s| ", s);
    }
}

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.

Undo by hand
// 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.

Shallow backup
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.

Memento
  • 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.

Itinerary.save()
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.

Itinerary.restore()
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.

UndoHistory
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.

Keep memory in check
  • 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.

Two ways to undo
  • 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 / skip it
  • 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.

Seen in Java
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.

Where it shows up
  • 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.

Avoid these
  • 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

Interview questions

What is the Memento pattern?

It lets an object capture its internal state in a snapshot object and restore that state later, without exposing the state to other classes. The object that creates the snapshot is the only one that can read it.

What are the roles in the Memento pattern?

The originator owns the state, creates mementos and restores from them. The memento holds a snapshot of the state. The caretaker stores mementos, for example on undo and redo stacks, but never reads or changes their contents.

How do you keep a memento opaque in Java?

Expose only a small public interface or marker type to the caretaker, and implement it with a private nested class or record inside the originator. Other classes can store and pass it around, but cannot name or read the real type.

Why must a memento copy mutable fields?

If the snapshot keeps a reference to a mutable object, like a list, later changes to the originator also change the snapshot, so restoring brings back the new state instead of the old one. Use defensive or immutable copies such as List.copyOf.

How would you implement undo and redo with mementos?

Keep two stacks. Before each change push a snapshot on the undo stack and clear the redo stack. On undo, pop from undo, push the current state onto redo and restore; redo does the reverse. Cap the undo stack to bound memory.

What is the difference between Memento and Command for undo?

Memento stores the previous state, which is simple and reliable but costs memory per step. Command stores the action and its inverse, which is cheaper but requires every action to have a correct undo. They are often combined.

What are the drawbacks of the Memento pattern?

Full snapshots can use a lot of memory when the state is large or history is deep. Mitigate with a history limit, snapshots only at meaningful steps, sharing immutable parts, or storing differences instead of full copies.

Where do you see the Memento idea in Java or databases?

JDBC savepoints are a close example: Connection.setSavepoint returns an opaque Savepoint, and Connection.rollback with it undoes the work done after that point. Undo stacks in editors and save files in games follow the same idea.