Memento

November 27, 202610 minutes

A platform game needs checkpoints. Learn how Memento lets the game snapshot its own private state, why the save slots must never read it, and when snapshots beat commands.

In a platform game, you reach a campfire, and the game remembers. Die three rooms later, and you wake up at the campfire, with the same health, the same spot, the same bag of items. So the game has to save its own state, and give it back later. Something has to hold on to those saves. Who should hold them, and how much should that holder be allowed to see? There’s a pattern for exactly this, and it’s called Memento.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

A coat check

Think of a coat check. You hand over your coat, and you get a ticket. The attendant hangs it up somewhere safe. The attendant never looks in your pockets. All they do is keep the coat, and hand it back to whoever shows the ticket. Only you, with the ticket, get your own coat back, just as you left it. And the attendant never needed to know what was inside.

In code, you are the originator, the object whose state matters. The coat is the memento, a snapshot of that state. The attendant is the caretaker. The caretaker holds something it can’t read. That’s the whole trick.

The coat check mapped onto code: you are the originator, the coat is the memento, and the attendant is the caretaker. The coat check mapped onto code: you are the originator, the coat is the memento, and the attendant is the caretaker.
The coat check, mapped onto the code.

The obvious version: open every field

Here’s the obvious version. Make the game’s fields public, so a SaveSlots class can reach them.

public class Game {
    public int x;
    public int health;
    public List<Item> inventory = new ArrayList<>();
}

SaveSlots copies the position, the health and the items out. To restore, it writes them straight back.

public class SaveSlots {
    private int x, health;
    private List<Item> inventory;

    public void save(Game game) {
        x = game.x;
        health = game.health;
        inventory = new ArrayList<>(game.inventory);
    }

    public void restore(Game game) {
        game.x = x;
        game.health = health;
        game.inventory = new ArrayList<>(inventory);
    }
}

It’s short, and it works. For one small game, that’s fair. (A variant with a getter and a setter for every field behaves the same way: the fields are just as open.)

Why it breaks

Then the team renames health, or splits it in two. SaveSlots stops compiling, and so does every other class that reached into the game. Worse, anything can write to those fields. One line sets health to 999, and nothing objects.

game.health = 999;

The real problem is where the knowledge lives. SaveSlots now knows exactly how the game keeps its state. Public fields give SaveSlots what it needs. They give everyone else the same access. refactoring.guru describes the same dilemma: copying an object’s state from the outside means either exposing its private fields, which makes the code fragile when fields change, or hiding them, which makes snapshots impossible.

The key idea: let the game save itself

So let the game save itself. It already knows its own fields, private or not, so it can pack them into a snapshot. The game hands that snapshot to SaveSlots, which has no idea what’s inside. All it can do is keep it. Later, SaveSlots hands the snapshot back, and the game unpacks it. Only the game can read what the game wrote.

The pattern’s intent, in short: capture an object’s state so you can roll it back, without breaking encapsulation.

Keep the ticket, not the coat.

Building it

Inside Game, two types do the work. A public interface called Save has no methods at all. It’s just a name the outside world can hold. The snapshot itself is a private record called Checkpoint. It holds the position, the health and a list of items, and it implements Save.

public class Game {
    public interface Save {}

    private record Checkpoint(int x, int health, List<Item> inventory)
            implements Save {}

    private int x;
    private int health;
    private List<Item> inventory = new ArrayList<>();

    // save(), restore(), moving and fighting below
}

Private means only the game’s own code can name it. Outside code can hold a Save, but it can’t even write the word Checkpoint. This is a rule of the language: a private member type is accessible only within the body of the top-level class that encloses it (JLS section 6.6.1). It is also why the design needs the interface. save() is a public method, so its return type has to be public too, and the private record is returned as a Save.

The save method packs the fields into a checkpoint, and hands it back as a Save. Keep an eye on the list line.

public Save save() {
    return new Checkpoint(x, health, inventory);   // the same list!
}

restore takes a Save and checks it really is a checkpoint (the instanceof pattern needs Java 16 or later). If it is, the game copies the fields back in.

public void restore(Save save) {
    if (!(save instanceof Checkpoint c)) {
        throw new IllegalArgumentException("not a checkpoint");
    }
    x = c.x();
    health = c.health();
    inventory = new ArrayList<>(c.inventory());
}

The caretaker is plain. SaveSlots keeps a stack of saves. checkpoint pushes a new one, and restoreLast looks at the front and hands it back. ArrayDeque.push adds at the front, and peek returns the front without removing it, so a death sends you back to the same campfire as often as you like.

public class SaveSlots {
    private final Deque<Game.Save> saves = new ArrayDeque<>();

    public void checkpoint(Game game) {
        saves.push(game.save());
    }

    public void restoreLast(Game game) {
        Game.Save last = saves.peek();
        if (last != null) {
            game.restore(last);
        }
    }
}

It never opens a save, and it couldn’t. It only knows the Save type, and that type has no methods. At a campfire, call checkpoint. After a death, call restoreLast. The game is back at the fire.

slots.checkpoint(game);    // at the campfire
// ... fight, pick things up, die ...
slots.restoreLast(game);   // back at the campfire

Notice what Game exposes: no field at all, only save() and restore().

Sequence: client code asks SaveSlots to checkpoint the game; SaveSlots calls save on Game, which packs its fields into a Checkpoint and returns it as an opaque Save that SaveSlots keeps. Later the client asks SaveSlots to restore the last one; SaveSlots passes the Save back to Game, which unpacks it. Sequence: client code asks SaveSlots to checkpoint the game; SaveSlots calls save on Game, which packs its fields into a Checkpoint and returns it as an opaque Save that SaveSlots keeps. Later the client asks SaveSlots to restore the last one; SaveSlots passes the Save back to Game, which unpacks it.
Save, then restore: the caretaker only carries the snapshot.

Shallow or deep

Now look at that list line. The checkpoint holds the very same list the game is still using. Save at the campfire with a sword. Pick up a key, then die. Restore, and the key is still in the bag, because the snapshot’s list changed along with the game’s.

Shallow versus deep snapshot. Shallow: the game and the checkpoint both point at one shared list holding a sword and, later, a key. Deep: the game's list holds the sword and the key, while the checkpoint points at its own copy of the list holding only the sword. Shallow versus deep snapshot. Shallow: the game and the checkpoint both point at one shared list holding a sword and, later, a key. Deep: the game's list holds the sword and the key, while the checkpoint points at its own copy of the list holding only the sword.
Shallow: one bag, two owners. Deep: two bags.

The fix is to copy the list when you save. List.copyOf makes a copy that nobody can modify. The Javadoc says later changes to the source collection are not reflected in the returned list, so later pickups can’t touch the snapshot.

public Save save() {
    return new Checkpoint(x, health, List.copyOf(inventory));
}

On restore, the game copies once more, into a fresh list it is free to change. That is why restore wraps the checkpoint’s list in a new ArrayList: copy in, and copy out.

This is the shallow and deep trap from the Prototype article. Here the items are immutable records, so copying the list is deep enough. (The same Javadoc warns that if the elements of an unmodifiable list are themselves mutable, their changes can still show through. Those would need their own copies.)

public record Item(String name) {}

A good rule: copy any part that can change, and share the parts that can’t.

Anatomy

Three roles. The originator is the game, which creates snapshots and restores from them. The memento is the checkpoint. The caretaker is SaveSlots.

Class diagram of Memento: Game creates Checkpoint, a private record that implements the Save interface; SaveSlots holds Saves in a deque and asks Game to save and restore. Class diagram of Memento: Game creates Checkpoint, a private record that implements the Save interface; SaveSlots holds Saves in a deque and asks Game to save and restore.
Three roles, two views of the memento.

From outside, the memento is only the Save type: a narrow view with nothing in it. Inside the game, the checkpoint is wide open. That is the same shape refactoring.guru describes: nested in the originator, the memento’s contents stay reachable for the originator while the caretaker can only store it.

A record can’t change after it’s built, and its list is unmodifiable, so a checkpoint stays exactly as taken. One honest caveat: reflection can bypass private. This is encapsulation, which protects you from accidents and from casual reach-ins, and it is not a security boundary.

To keep saves across restarts, Java serialization can write a memento to a file, as long as everything inside it is serializable. The ObjectOutputStream Javadoc says persistent storage of objects can be done by using a file for the stream, and that only objects that support java.io.Serializable can be written. Records can implement Serializable.

What it costs

Snapshots aren’t free. Every checkpoint holds a copy of the state, so take them too often and memory fills up. refactoring.guru lists it as the main con: “The app might consume lots of RAM if clients create mementos too often.”

Three ways to keep it in check:

  1. Limit the history. Drop the oldest save when there are too many.
  2. Store only what changed since the last snapshot (a diff).
  3. Snapshot only the fields that actually change.
public void checkpoint(Game game) {
    saves.push(game.save());
    if (saves.size() > 3) {
        saves.removeLast();
    }
}

push adds at the front, so removeLast drops the oldest. The caretaker has a chore too: it should drop saves it will never restore. Each option buys memory with more code.

A second example: undo in an editor

Undo in a text editor. Before every edit, the editor pushes a snapshot of the text and the cursor. undo pops the last snapshot and puts it back. The snapshot is a private record, so only the editor can read it. (Here the editor plays originator and caretaker at once, which is fine when nobody outside needs the history.)

public class Editor {
    private record Snapshot(String text, int cursor) {}

    private String text = "";
    private int cursor;
    private final Deque<Snapshot> history = new ArrayDeque<>();

    public void type(String more) {
        history.push(new Snapshot(text, cursor));
        text = text.substring(0, cursor) + more + text.substring(cursor);
        cursor += more.length();
    }

    public void undo() {
        if (!history.isEmpty()) {
            Snapshot s = history.pop();
            text = s.text();
            cursor = s.cursor();
        }
    }
}

Strings never change, so a snapshot can simply keep the old string. But every edit then keeps the whole document again.

The Command pattern solves the same problem another way. It stores each edit and how to reverse it, like insert this word here and delete it again.

Snapshots (Memento)Commands
What is storedthe whole state, per editthe edit and its inverse
Strengthsimpler, and works for any changesmaller when the state is big
Weaknessmemory grows with the stateevery edit needs a working inverse

The two also combine: refactoring.guru describes a command that takes a memento of its target just before it runs, and restores from it to undo.

The mix-up: a getter for every field

A common mix-up: a memento is just a getter for every field. That’s the obvious version again, with extra steps. If SaveSlots can read every field, encapsulation is gone. The point is that the originator makes the memento, and the originator reads it. Nobody else can.

When not to use it

When should you skip it?

  • The state is huge. Whole copies get expensive. Use commands or diffs instead.
  • The state is already immutable. Just keep the old reference. That’s a snapshot for free.
  • The state includes things outside the program, like open files or network connections. A snapshot can’t capture them.
Decision: is the state huge? Use commands or diffs. Is it already immutable? Keep the old reference. Does it include files or sockets? A snapshot can't capture it. Otherwise use a memento: snapshot, copy the mutable parts, cap the history. Decision: is the state huge? Use commands or diffs. Is it already immutable? Keep the old reference. Does it include files or sockets? A snapshot can't capture it. Otherwise use a memento: snapshot, copy the mutable parts, cap the history.
Is a snapshot the right tool?

Recap

  • The game packs its own state into a snapshot, and only the game can read it.
  • SaveSlots keeps snapshots it can’t read.
  • Copy whatever can change, and keep the history short.
  • Skip it for huge state, immutable state, or things outside the program.
Recap chain: the game packs its state into a snapshot, the save slots keep it unread, the game unpacks it. Recap chain: the game packs its state into a snapshot, the save slots keep it unread, the game unpacks it.
Pack it, hold it, unpack it.

Checklist:

  • Does the object own state that someone else needs to roll back to, but must not read?
  • Is the snapshot a type only the originator can name (a private record behind a marker interface)?
  • Is every mutable part copied on the way in and on the way out?
  • Is the history bounded, with old saves dropped?
  • Would commands, diffs, or just keeping an immutable reference be smaller or simpler?

Keep the ticket, not the coat.

Related lessons: Prototype (shallow vs deep), Command (undo with operations).

Further reading

  • Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns (1994): Memento.
  • refactoring.guru: Memento.
  • List.copyOf Javadoc.
  • Serializable and ObjectOutputStream Javadoc.
  • The Java Language Specification, section 6.6.1 (Determining Accessibility).