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.
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.
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.)
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.
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.
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 campfireNotice what Game exposes: no field at all, only save() and restore().
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.
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.
Three roles. The originator is the game, which creates snapshots and restores from them. The
memento is the checkpoint. The caretaker is SaveSlots.
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.
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:
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.
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 stored | the whole state, per edit | the edit and its inverse |
| Strength | simpler, and works for any change | smaller when the state is big |
| Weakness | memory grows with the state | every 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.
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 should you skip it?
SaveSlots keeps snapshots it can’t read.Checklist:
Keep the ticket, not the coat.
Related lessons: Prototype (shallow vs deep), Command (undo with operations).
List.copyOf Javadoc.Serializable and
ObjectOutputStream Javadoc.