LLD

Behavioral Patterns

Memento pattern

A save system needs a copy of the game's state, but it should not be able to read or change that state. We build game saves twice, once with getters and setters and once with the Memento pattern, and look at what each version costs.

A game has a Save button. You save before a hard fight, lose, and load the save. The game comes back exactly as it was: same place, same health, same items. Nothing you did after saving leaks in.

Many programs need this. A drawing app restores the canvas when you undo a filter. A long form keeps a draft. A setup wizard goes back a step. In each one, something else must hold on to a copy of an object's state and give it back later, and the object's insides should stay private while it waits.

The Memento pattern does this. The object makes a sealed copy of its own state. Another object keeps the copy without being able to look inside, and hands it back when it is needed. In this article we build the saves for a small game twice. The first version lets the save system read and write the game directly. The second uses the Memento pattern. Then we look at what the pattern costs, how it differs from the Command pattern, and how it shows up in interviews.

All the code is Java. Every snippet comes from one of two projects that compile and run, except the ones labelled Sketch, and the Open file button on a snippet from the finished project shows the whole file in a code browser.

The saves we are building

The game's state is four things: the current level, the player's position, the player's health (0 to 100) and a bag of up to 10 items. The saves must do this:

  1. The player can save to one of 3 numbered slots, with a label such as "Before the boss", and load any slot later.
  2. Starting the game and entering a level each make an automatic checkpoint. The game keeps the last 5. When the player dies, the game goes back to the latest one.
  3. A loaded game is exactly the game as it was saved. Nothing done after saving changes the save.
  4. The save slots and the checkpoint history store saves and hand them back. They cannot reach the fields inside one.
  5. A save from another player's game, or a damaged file, is refused with a message, and the current game does not change.
  6. Slots survive a restart of the game.
Saving and loading, at a glance
The game makes a checkpoint of its own state (1). The save slots or the checkpoint history store it (2), and they can list it or hand it back but cannot reach its fields (3). To load, the checkpoint goes back to the game (4), which checks that it belongs to this game and copies the saved state back into itself. The amber dot marks a sealed checkpoint.The game makes a checkpoint of its own state (1). The save slots or the checkpoint history store it (2), and they can list it or hand it back but cannot reach its fields (3). To load, the checkpoint goes back to the game (4), which checks that it belongs to this game and copies the saved state back into itself. The amber dot marks a sealed checkpoint.
The game makes a sealed copy of itself. Others keep it but cannot reach its fields. The game makes a checkpoint of its own state (1). The save slots or the checkpoint history store it (2), and they can list it or hand it back but cannot reach its fields (3). To load, the checkpoint goes back to the game (4), which checks that it belongs to this game and copies the saved state back into itself. The amber dot marks a sealed checkpoint.

This is the picture to draw first in an interview: three parts, and one rule that only the object that made a copy can read its fields.

The first version: the save system reads the game

The obvious version gives the save system a getter and a setter for every field of the game. Saving reads every field into a SaveData object. Loading writes every field back:

SaveSlots.javalines 7–24 of 30
    public void save(int slot, Game game) {        SaveData data = new SaveData();        data.level = game.getLevel();        data.x = game.getX();        data.y = game.getY();        data.health = game.getHealth();        data.inventory = game.getInventory();        slots.put(slot, data);    }     public void load(int slot, Game game) {        SaveData data = slots.get(slot);        game.setLevel(data.level);        game.setX(data.x);        game.setY(data.y);        game.setHealth(data.health);        game.setInventory(data.inventory);    }

For the save system to do this, the game has to open every field to the outside:

Game.javalines 52–66 of 67
    public int getHealth() {        return health;    }     public void setHealth(int health) {        this.health = health;    }     public List<String> getInventory() {        return inventory;    }     public void setInventory(List<String> inventory) {        this.inventory = inventory;    }

The before version's demo saves, picks up a potion, takes damage, loads, and sets the health from outside:

$ java Main
> Save to slot 1
  slot 1 holds health 100, bag [sword]
> Pick up a potion, take 30 damage
  slot 1 holds health 100, bag [sword, potion]
> Load slot 1
  level 1, at (0, 0), health 100, bag [sword, potion]
> Any code can call setHealth(999)
  level 1, at (0, 0), health 999, bag [sword, potion]

For a game whose state is a few numbers, used by one trusted class, this version is fine. It goes wrong here in three ways.

The save shares the bag. Line 13 stores game.getInventory(), which is the game's own list, not a copy, and line 23 hands that same list back on load. When the player picks up the potion, the saved slot gets the potion too. After loading, health is back to 100 but the potion is still in the bag: half of the game is from the save and half is from after it.

The game's rules can be skipped. The game keeps health between 0 and 100 inside takeDamage. setHealth exists only for loading, but it is public, so any code can call setHealth(999) and the rule never runs.

Every new field touches four places. A gold field needs a getter and setter in Game, a field in SaveData, a line in save and a line in load. If the line in save is forgotten, the code still compiles, and every load silently sets gold to 0.

What the first version opens up
SaveSlots reads every field through a getter and writes it back through a setter, so the game must make all of them public. The bag is copied by reference: the game and the saved slot point at the same list, shown in red, so a potion picked up after saving appears in the save too. Any other code can use the same setters, such as setHealth(999).SaveSlots reads every field through a getter and writes it back through a setter, so the game must make all of them public. The bag is copied by reference: the game and the saved slot point at the same list, shown in red, so a potion picked up after saving appears in the save too. Any other code can use the same setters, such as setHealth(999).
The save system reaches into the game, and the saved bag is the game's own list. SaveSlots reads every field through a getter and writes it back through a setter, so the game must make all of them public. The bag is copied by reference: the game and the saved slot point at the same list, shown in red, so a potion picked up after saving appears in the save too. Any other code can use the same setters, such as setHealth(999).

The idea

The Memento pattern moves the copying into the object whose state is saved:

  • The game makes the copy itself. save() returns a checkpoint of its own state.
  • The checkpoint is sealed. Only the game can read the fields inside it.
  • Other objects keep checkpoints. The save slots and the checkpoint history store them, list them and hand them back. They cannot reach their fields.
  • To load, a checkpoint goes back to the game's restore(), which checks it and copies the saved state back in.

The parts have names. The game is the originator, the checkpoint is the memento, and whatever keeps checkpoints is the caretaker. This matches how the Command page describes Memento: the object makes its own sealed copy, and the history holds it without being able to read or change what is inside.

Building it, step by step

Step 1: a checkpoint only the game can read

The checkpoint is a class nested inside Game. Its fields are private, and so is its constructor:

game/Game.javalines 98–118 of 198
    // The fields are private, so only Game, the class around this one, can read them.    public static final class Checkpoint {        public static final int MAX_BYTES = 4096;        private static final String FORMAT = "game-save";        private static final String HEADER = FORMAT + " v1";        private static final Pattern ANY_VERSION = Pattern.compile(FORMAT + " v[0-9]{1,6}");        private static final Pattern NUMBER = Pattern.compile("-?[0-9]{1,10}");         private final String gameId;        private final int level;        private final Position position;        private final Health health;        private final List<String> items;         private Checkpoint(String gameId, int level, Position position, Health health, List<String> items) {            this.gameId = gameId;            this.level = level;            this.position = position;            this.health = health;            this.items = items;        }

In Java, the class around a nested class can read the nested class's private fields, and no other class can. So Game reads checkpoint.health, while SaveSlots, which holds the same object, cannot. The constructor is private and the class is final, so no other class can extend it, and a subclass could not see the private fields anyway. The default toString prints only the class name and a number.

Decision

How is a checkpoint sealed?

A record

A record is the shortest way to write a class that holds data. But every field gets a public accessor, and toString prints all of them. Any code that holds a checkpoint can read the player's health and items, which is what the first version did with getters. The difference from our choice is coupling, not secrecy: accessors let other code start to depend on the fields.

A top-level class with package-private fields

The checkpoint goes in its own file in package game, with no access modifier on its fields. Classes outside game cannot read it. But every class added to game later can, and nothing in the code marks that as wrong.

A nested class with private fieldsOur pick

Only Game can reach the fields, and the compiler stops any other class from doing so. The cost is a longer Game.java, because the checkpoint and its file format live inside it.

The checkpoint still has two public methods, toBytes and fromBytes, for writing it to disk. They are its narrow interface: all a caretaker needs to store it. The private fields are its wide interface, and only Game uses them. The narrow side is a deliberate opening. Any code can call toBytes and read the state as text, and any code can call fromBytes with values of its choosing, as long as they pass the checks. The seal stops other code from depending on the game's fields. It does not keep the state secret, and Step 5 says what would.

Step 2: save copies out, restore copies back

save() builds a checkpoint from the current state, and restore() copies a checkpoint's state back:

game/Game.javalines 63–76 of 198
    public Checkpoint save() {        return new Checkpoint(gameId, level, position, health, bag.items());    }     public void restore(Checkpoint checkpoint) {        Objects.requireNonNull(checkpoint, "checkpoint");        if (!checkpoint.gameId.equals(gameId)) {            throw new SaveRejectedException("This save belongs to another game");        }        level = checkpoint.level;        position = checkpoint.position;        health = checkpoint.health;        bag.replaceWith(checkpoint.items);    }

Look at what is copied. level is an int. position and health are records that never change once made: takeDamage replaces the Health object instead of changing it. Sharing such values between the game and a checkpoint is safe, because neither side can change them.

The bag is different. Inventory holds a list that add and remove change. So the checkpoint must not hold the game's bag. It holds a copy of the item names, made by bag.items():

game/Inventory.javalines 30–37 of 45
    public List<String> items() {        return List.copyOf(items);    }     void replaceWith(List<String> newItems) {        items.clear();        items.addAll(newItems);    }

items() returns List.copyOf, an unchangeable copy. replaceWith clears the bag and adds the saved names one by one, so after a restore the game's bag and the checkpoint's list are still separate. The game can pick up a shield, and the checkpoint still says the bag held a sword.

Decision

How much does a checkpoint copy?

The game's Inventory object

This is one line and no copying. It is also the first version's bug: the checkpoint and the game share one bag, so later play changes the save.

A copy of the item namesOur pick

The list is copied, and the names inside are strings, which never change. One level of copying is therefore enough. The records for position and health need no copy at all.

A deep copy of every object

If items were objects that change, such as a sword that wears out with each use, copying the list would not be enough: the copy would point at the same sword objects. Each item would need its own copy. Our items are names, so we do not need this, but it is the first question to ask about any state with nested parts.

Step 3: refuse a checkpoint that does not belong

Every checkpoint carries the id of the game that made it, such as asha-run-1. restore() checks the id before it changes anything (lines 69 to 71 above). If two players share a computer and one loads the other's save, the game throws SaveRejectedException with the message "This save belongs to another game", and the current game is untouched.

The order matters: if restore copied the level before checking the id, a refused load would leave the game half-changed.

The game uses three kinds of error. SaveRejectedException is for problems a player can meet, such as another game's save or a damaged file, and its message is written for the player. IllegalStateException is for the rules of play, such as a full bag or a dead player trying to move. IllegalArgumentException and NullPointerException are programmer errors, such as a level of 0 or a null checkpoint.

Step 4: keeping checkpoints

The automatic checkpoints live in AutoSaves, a caretaker that keeps a fixed number of them:

save/AutoSaves.javalines 26–42 of 43
    public void record(Game.Checkpoint checkpoint) {        Objects.requireNonNull(checkpoint, "checkpoint");        if (checkpoints.size() == capacity) {            checkpoints.removeFirst();        }        checkpoints.addLast(checkpoint);    }     public Optional<Game.Checkpoint> latest() {        return Optional.ofNullable(checkpoints.peekLast());    }     public List<Game.Checkpoint> newestFirst() {        List<Game.Checkpoint> list = new ArrayList<>(checkpoints);        Collections.reverse(list);        return List.copyOf(list);    }

record adds a checkpoint at the end. When the history is full, it first removes the oldest one from the front. latest() gives the newest one for when the player dies. newestFirst() gives all of them, for a menu that lets the player go back further.

AutoSaves never calls anything on a checkpoint. Moving references around is the whole job of a caretaker.

Something still has to make a checkpoint when a level starts, and go back to one when the player dies. That is PlaySession, the object the game loop calls:

play/PlaySession.javalines 12–39 of 44
    public PlaySession(Game game, AutoSaves autoSaves) {        this.game = Objects.requireNonNull(game, "game");        this.autoSaves = Objects.requireNonNull(autoSaves, "autoSaves");        if (game.isDead()) {            throw new IllegalArgumentException("A session starts with a living player");        }        // A checkpoint at the start, so a death always has somewhere to go back to.        autoSaves.record(game.save());    }     public void enterLevel(int level) {        game.enterLevel(level);        autoSaves.record(game.save());    }     public void load(Game.Checkpoint checkpoint) {        game.restore(checkpoint);        autoSaves.record(checkpoint);    }     public boolean takeDamage(int amount) {        game.takeDamage(amount);        if (!game.isDead()) {            return false;        }        game.restore(autoSaves.latest().orElseThrow());        return true;    }

The constructor refuses a dead player, then makes a checkpoint at once (line 19), so a death in the first minute still has somewhere to go back to. enterLevel makes one after the level starts (line 24). load restores a save and records it as the newest checkpoint (lines 28 and 29). Without that, loading an old save and then dying would jump forward to a checkpoint made after it. takeDamage restores the latest checkpoint on death (line 37). Each session needs its own AutoSaves, or a death could hand back another player's checkpoint, which restore refuses. Entering a level twice fills two places with near-copies.

Decision

What happens when the history is full?

Refuse the new checkpoint

The history then keeps the oldest progress and loses the newest, which is the opposite of what a player who just died needs.

Keep every checkpoint

Nothing is ever lost, but a long session keeps growing in memory, one full copy of the state per level.

Drop the oldestOur pick

The player can always go back to recent progress, and memory stays bounded at 5 copies. A checkpoint from an hour ago is gone, which is acceptable because the save slots exist for keeping a game on purpose.

The save slots live in SaveSlots, a second caretaker. It has a fixed number of slots, and saving to a used slot replaces what was there, because the player chose that slot. Unlike AutoSaves, it writes to disk.

Step 5: writing a checkpoint to disk

A caretaker that writes to disk needs the checkpoint as bytes. The checkpoint turns itself into bytes, so the caretaker still never reads a field:

game/Game.javalines 120–129 of 198
        public byte[] toBytes() {            String body = String.join("\n",                    HEADER,                    "game=" + gameId,                    "level=" + level,                    "position=" + position.x() + "," + position.y(),                    "health=" + health.points(),                    "bag=" + String.join("|", items));            return (body + "\ncrc=" + crcOf(body) + "\n").getBytes(StandardCharsets.UTF_8);        }

The format is plain text: a header line with a version, one line per value, and a checksum of everything above it. SaveSlots puts its own line in front, the slot's label, and writes the file:

save/SaveSlots.javalines 38–65 of 139
    public void save(int slot, String label, Game.Checkpoint checkpoint) throws IOException {        Path file = fileFor(slot);        checkLabel(label);        Objects.requireNonNull(checkpoint, "checkpoint");        byte[] header = (LABEL + label + "\n").getBytes(StandardCharsets.UTF_8);        byte[] payload = checkpoint.toBytes();        byte[] contents = Arrays.copyOf(header, header.length + payload.length);        System.arraycopy(payload, 0, contents, header.length, payload.length);         Path temporary = Files.createTempFile(folder, file.getFileName() + "-", ".tmp");        try {            writeAndFlush(temporary, contents);            Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);        } catch (Throwable e) {            deleteQuietly(temporary, e);            throw e;        }    }     private static void writeAndFlush(Path temporary, byte[] contents) throws IOException {        try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {            ByteBuffer buffer = ByteBuffer.wrap(contents);            while (buffer.hasRemaining()) {                channel.write(buffer);            }            channel.force(true);        }    }

The label is the caretaker's own data, so it sits outside the checkpoint's bytes. The bytes go to a temporary file first, and force makes the disk store them (line 63). Then the temporary file is moved over the old save in one step. If the program crashes while writing, the old save is still whole. Surviving a power cut as well would also need the folder flushed after the swap. If any step fails, the temporary file is deleted, and any failure to delete is attached to the original error instead of replacing it.

Loading goes the other way. SaveSlots reads the file, strips its label line and passes the rest to Checkpoint.fromBytes. That method refuses a file that is too big, one that is not a save, and one from another version of the game. It then checks the checksum and every value: health from 0 to 100, a level of at least 1, at most 10 item names, each name valid. Any failure gives "This save file is damaged".

Decision

Who turns a checkpoint into bytes?

The save system, reading each field

The save system would write a JSON file with health, level and items. To do that it needs to read every field, which undoes Step 1, and every new field touches the saver again.

Java's built-in serialization

The checkpoint would implement Serializable and Java would write its private fields. The file format then follows those fields, so changing them can break old saves or quietly damage them. Reading a file a player can edit also creates objects of ordinary classes without running their constructors, so the checks in a constructor are skipped.

The checkpoint writes and reads its own formatOur pick

The format is chosen on purpose and checked on the way in, and it can change without breaking old saves. The cost is the parsing code in fromBytes.

The bytes are not secret, from code or from people. Any code can call toBytes and read health=75, and anyone can open a save file in a text editor. The checksum catches a file damaged by a crash or a bad disk, and it catches a careless edit. Code or a player that works out a new checksum can still make a checkpoint with 99 health, or relabel another game's save as their own. A single-player game accepts that. Secrecy, or refusing forged saves, would need encryption or a signature with a key the player does not have.

The version in the header is what lets the format change later. A version 2 that adds gold would read both versions, giving version 1 saves a gold of 0. Today, any version other than 1 is refused with "This save comes from a different version of the game", instead of being loaded wrongly.

The finished design

The finished design
Game owns its Inventory and uses the Health and Position records. It creates Checkpoint, which is nested inside it, and only Game can reach a checkpoint's fields. AutoSaves holds checkpoints in memory. SaveSlots writes and reads them on disk through toBytes and fromBytes. PlaySession records a checkpoint in AutoSaves at the start and on each new level, and restores the game when the player dies. SaveRejectedException is the error a player can see.Game owns its Inventory and uses the Health and Position records. It creates Checkpoint, which is nested inside it, and only Game can reach a checkpoint's fields. AutoSaves holds checkpoints in memory. SaveSlots writes and reads them on disk through toBytes and fromBytes. PlaySession records a checkpoint in AutoSaves at the start and on each new level, and restores the game when the player dies. SaveRejectedException is the error a player can see.
The game makes and reads checkpoints. The caretakers only keep them. Game owns its Inventory and uses the Health and Position records. It creates Checkpoint, which is nested inside it, and only Game can reach a checkpoint's fields. AutoSaves holds checkpoints in memory. SaveSlots writes and reads them on disk through toBytes and fromBytes. PlaySession records a checkpoint in AutoSaves at the start and on each new level, and restores the game when the player dies. SaveRejectedException is the error a player can see.

Here is one load, traced through the objects:

Loading slot 1, traced
The menu asks SaveSlots for slot 1 (1). SaveSlots reads the file, drops its label line, and passes the bytes to Checkpoint.fromBytes (2), which checks the version, the checksum and every value. The checkpoint goes back to the menu (3), which hands it to the game (4). The game checks the game id and copies the saved state in, and the bag replaces its items (5).The menu asks SaveSlots for slot 1 (1). SaveSlots reads the file, drops its label line, and passes the bytes to Checkpoint.fromBytes (2), which checks the version, the checksum and every value. The checkpoint goes back to the menu (3), which hands it to the game (4). The game checks the game id and copies the saved state in, and the bag replaces its items (5).
The caretaker reads the file. Only the game reads the checkpoint. The menu asks SaveSlots for slot 1 (1). SaveSlots reads the file, drops its label line, and passes the bytes to Checkpoint.fromBytes (2), which checks the version, the checksum and every value. The checkpoint goes back to the menu (3), which hands it to the game (4). The game checks the game id and copies the saved state in, and the bag replaces its items (5).

The whole project is below. Click any class name in the code to open that class.

gameGame.java
package game; import java.nio.charset.StandardCharsets;import java.util.Arrays;import java.util.List;import java.util.Objects;import java.util.regex.Pattern;import java.util.zip.CRC32; public class Game {    private static final Pattern GAME_ID = Pattern.compile("[A-Za-z0-9-]{1,40}");     private final String gameId;    private int level = 1;    private Position position = new Position(0, 0);    private Health health = Health.full();    private final Inventory bag = new Inventory();     public Game(String gameId) {        this.gameId = checkGameId(gameId);    }     public void enterLevel(int newLevel) {        requireAlive();        checkLevel(newLevel);        level = newLevel;        position = new Position(0, 0);    }     public void moveTo(Position to) {        Objects.requireNonNull(to, "to");        requireAlive();        position = to;    }     public void takeDamage(int amount) {        health = health.minus(amount);    }     public void heal(int amount) {        requireAlive();        health = health.plus(amount);    }     public void pickUp(String item) {        requireAlive();        bag.add(item);    }     public void drop(String item) {        bag.remove(item);    }     public boolean isDead() {        return health.isZero();    }     public String status() {        return "level " + level + ", at (" + position.x() + ", " + position.y() + "), health "                + health.points() + ", bag " + bag.items();    }     public Checkpoint save() {        return new Checkpoint(gameId, level, position, health, bag.items());    }     public void restore(Checkpoint checkpoint) {        Objects.requireNonNull(checkpoint, "checkpoint");        if (!checkpoint.gameId.equals(gameId)) {            throw new SaveRejectedException("This save belongs to another game");        }        level = checkpoint.level;        position = checkpoint.position;        health = checkpoint.health;        bag.replaceWith(checkpoint.items);    }     private void requireAlive() {        if (isDead()) {            throw new IllegalStateException("The player is dead");        }    }     private static String checkGameId(String gameId) {        Objects.requireNonNull(gameId, "gameId");        if (!GAME_ID.matcher(gameId).matches()) {            throw new IllegalArgumentException("A game id is 1 to 40 letters, digits and hyphens: " + gameId);        }        return gameId;    }     private static void checkLevel(int level) {        if (level < 1) {            throw new IllegalArgumentException("Levels start at 1, got " + level);        }    }     // The fields are private, so only Game, the class around this one, can read them.    public static final class Checkpoint {        public static final int MAX_BYTES = 4096;        private static final String FORMAT = "game-save";        private static final String HEADER = FORMAT + " v1";        private static final Pattern ANY_VERSION = Pattern.compile(FORMAT + " v[0-9]{1,6}");        private static final Pattern NUMBER = Pattern.compile("-?[0-9]{1,10}");         private final String gameId;        private final int level;        private final Position position;        private final Health health;        private final List<String> items;         private Checkpoint(String gameId, int level, Position position, Health health, List<String> items) {            this.gameId = gameId;            this.level = level;            this.position = position;            this.health = health;            this.items = items;        }         public byte[] toBytes() {            String body = String.join("\n",                    HEADER,                    "game=" + gameId,                    "level=" + level,                    "position=" + position.x() + "," + position.y(),                    "health=" + health.points(),                    "bag=" + String.join("|", items));            return (body + "\ncrc=" + crcOf(body) + "\n").getBytes(StandardCharsets.UTF_8);        }         public static Checkpoint fromBytes(byte[] bytes) {            Objects.requireNonNull(bytes, "bytes");            if (bytes.length > MAX_BYTES) {                throw new SaveRejectedException("This is not a save file");            }            String[] lines = new String(bytes, StandardCharsets.UTF_8).split("\n", -1);            if (!ANY_VERSION.matcher(lines[0]).matches()) {                throw new SaveRejectedException("This is not a save file");            }            if (!lines[0].equals(HEADER)) {                throw new SaveRejectedException("This save comes from a different version of the game");            }            if (lines.length != 8 || !lines[7].isEmpty()) {                throw damaged();            }            String body = String.join("\n", Arrays.copyOfRange(lines, 0, 6));            if (!lines[6].equals("crc=" + crcOf(body))) {                throw damaged();            }            try {                String gameId = checkGameId(value(lines[1], "game"));                int level = number(value(lines[2], "level"));                checkLevel(level);                String[] xy = value(lines[3], "position").split(",", -1);                if (xy.length != 2) {                    throw damaged();                }                Position position = new Position(number(xy[0]), number(xy[1]));                Health health = new Health(number(value(lines[4], "health")));                String bag = value(lines[5], "bag");                List<String> items = bag.isEmpty() ? List.of() : List.of(bag.split("\\|", -1));                if (items.size() > Inventory.MAX_ITEMS) {                    throw damaged();                }                for (String item : items) {                    Inventory.checkName(item);                }                return new Checkpoint(gameId, level, position, health, items);            } catch (IllegalArgumentException e) {                throw damaged();            }        }         private static int number(String text) {            if (!NUMBER.matcher(text).matches()) {                throw damaged();            }            return Integer.parseInt(text);        }         private static String value(String line, String key) {            if (!line.startsWith(key + "=")) {                throw damaged();            }            return line.substring(key.length() + 1);        }         private static String crcOf(String body) {            CRC32 crc = new CRC32();            crc.update(body.getBytes(StandardCharsets.UTF_8));            return Long.toHexString(crc.getValue());        }         private static SaveRejectedException damaged() {            return new SaveRejectedException("This save file is damaged");        }    }}
Click a class name in the code to open its fileJava · 198 lines · 615 in the project

The demo in demo/Main.java plays through every case:

$ java demo.Main
> New game asha-run-1 (a checkpoint is made)
  level 1, at (0, 0), health 100, bag []
> Enter level 2 (a checkpoint is made)
  level 2, at (0, 0), health 100, bag []
> Pick up a sword, walk to (12, 4)
  level 2, at (12, 4), health 100, bag [sword]
> Save to slot 1, "Before the boss"
> Pick up a potion, take 30 damage
  level 2, at (12, 4), health 70, bag [sword, potion]
> Load slot 1
  level 2, at (12, 4), health 100, bag [sword]
> Take 150 damage (died, back to the latest checkpoint: true)
  level 2, at (12, 4), health 100, bag [sword]
> The slot menu
  1: Before the boss
  2: (empty)
  3: (empty)
> Restart the game and load slot 1
  level 2, at (12, 4), health 100, bag [sword]
> Load slot 2, a copy of slot 1 edited by hand to health 999
  Refused: This save file is damaged
> Load slot 1 into another player's game
  Refused: This save belongs to another game

Automatic checkpoints are made when the game starts and on entering level 2, before the sword. Slot 1 is saved after the sword, at (12, 4). Picking up a potion and taking 30 damage does not touch slot 1: loading it brings back health 100 and a bag with only the sword. Loading slot 1 also records it as the newest checkpoint, so when 150 damage kills the player, the session goes straight back to it: level 2, at (12, 4), with the sword. A new game started after a "restart" loads slot 1 from disk exactly. A copy of slot 1 edited by hand to health 999 is refused as damaged, because its checksum no longer matches. Slot 1 loaded into another player's game is refused too.

What it costs

Adding a field is cheaper than before. A gold field changes Game and the checkpoint inside it: a field in each, the lines in save and restore, and the two format methods with a version bump. All of it is in one file. SaveSlots and AutoSaves do not change at all.

Adding a gold field
In the first version (left), a new field touches Game, SaveData, the save method and the load method, shown in amber, and forgetting any of them still compiles. With the Memento pattern (right), only Game and its nested Checkpoint change. The caretakers, SaveSlots and AutoSaves, stay as they are.In the first version (left), a new field touches Game, SaveData, the save method and the load method, shown in amber, and forgetting any of them still compiles. With the Memento pattern (right), only Game and its nested Checkpoint change. The caretakers, SaveSlots and AutoSaves, stay as they are.
With the Memento pattern, the change stays inside the game. In the first version (left), a new field touches Game, SaveData, the save method and the load method, shown in amber, and forgetting any of them still compiles. With the Memento pattern (right), only Game and its nested Checkpoint change. The caretakers, SaveSlots and AutoSaves, stay as they are.

Every checkpoint is a full copy. Here a copy is a few numbers and at most 10 names. In a game whose world has thousands of objects, five full copies can be large. A checkpoint could store only what changed since the previous one, but then restoring needs every checkpoint in the chain, and losing one breaks all the ones after it. The Command pattern takes the other route and stores the changes as actions.

The game runs on one thread, so save() sees one moment. Saving from another thread would need one lock shared with every method that changes the game.

Undo and redo would need their own stacks. AutoSaves drops old checkpoints by itself and cannot take one off the end. An undo would push game.save() onto a redo stack and restore the top of a separate undo stack. Redo does the reverse, as on the Command page.

The seal holds against mistakes, not attackers. toBytes gives the state as text, reflection can still read private fields, and the file can be read by anyone. The pattern stops other parts of the program from depending on the game's insides by accident. It does not keep a secret.

When the pattern is too much

If the whole state is one value that never changes, it already is a safe snapshot, and keeping the old value is enough:

Sketchnot part of the final code
record Settings(int volume, boolean subtitles) {} Settings saved = current;current = new Settings(80, true);current = saved;

Settings cannot be changed after it is made, so the saved value stays as it was, and nothing outside the settings screen holds it. The Memento pattern earns its place when the state has parts that change, and when another object has to keep the copy.

Memento or Command?

Both give a way back, and the Command page compares them from the other side. The two pages give the same answer:

MementoCommand
What each step storesThe state: a copy of the object before the changeThe change: what was done and how to reverse it
Size of a stepThe size of the objectThe size of the edit
Knows what happenedNo, only what the state wasYes, each step is "insert" or "delete"
Can be replayed on another copyNo, it would overwrite that copy's own stateYes, as the same change
RiskMemory, for large objectsA wrong reverse corrupts the state

A short way to say it: a command remembers what you did, a memento remembers what it was.

Memento is also easy to confuse with Prototype, because both copy an object. A prototype is a live copy made to be used as a new object. A memento is a passive, sealed copy made to be given back to the object it came from.

In an interview

The Memento pattern sits inside design questions about going back: game saves and checkpoints, undo in a drawing app, a form that keeps drafts, and a document with versions. In each of them, the pattern answers one question: how does a user get back to an earlier state?

We suggest presenting it in this order:

  1. Say what state must come back. List the fields, and mark the ones that can change after they are made, such as a list.
  2. Name the three parts. Say who makes the copy (the object itself), who keeps it, and that the keeper cannot reach its fields.
  3. Show the copy. Write save() and restore(), and say which parts are copied and which are shared because they never change.
  4. Finish with the limits. Say what happens when the history is full, what is refused on load, and how the copy is written to disk.

Common mistakes:

  • A memento with getters, or a record. Any code that holds one can read the state, and often change it.
  • Saving a reference to a part that changes. The saved bag is the live bag, so later play changes the save.
  • Restoring field by field with a check in the middle. A refused load leaves the object half-restored. Check everything first, then copy.
  • A history with no limit. One full copy per checkpoint grows for as long as the program runs.
  • Built-in serialization for save files. The file then depends on the class's private fields, and old saves break or change meaning when those fields change.

Summary

  • Use the Memento pattern when another object must keep a copy of an object's state and hand it back later, without reaching its fields.
  • The object makes and reads its own mementos. In Java, a nested class with private fields stops other code from reaching them.
  • Copy every part that can change. Share only values that can never change, such as records and strings.
  • Check a memento completely before restoring anything from it.
  • Caretakers store, list and drop mementos, and keep a limit on how many.
  • For disk, let the memento write its own versioned format, and say plainly that the file is readable by anyone.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.