Command Palette

Search for a command to run...

PHASE 2Beginner ~7 min· topic 21 of 22Behavioral

Behavioral 9 — Memento

In one line

Save a snapshot of an object's state so you can restore it later, without exposing its private fields. Think 'save game' in a video game.

0/22 · 0%

Think of it like this

The save point in a video game. You save before the boss fight; if you lose, you load the save and everything is exactly as it was.

Key ideas

  1. 01

    Three roles: Originator (the object that has state, e.g. the editor), Memento (the sealed snapshot), Caretaker (keeps the list of snapshots, e.g. the history).

  2. 02

    The caretaker can store and hand back mementos but can't read or change what's inside them. That keeps encapsulation intact.

  3. 03

    Command vs Memento for undo: Command stores 'how to reverse the action' (small, but every action needs an undo). Memento stores 'the whole state before' (simple, but uses more memory).

  4. 04

    Used in: text editor undo, game checkpoints, form drafts, and transaction rollback in a database.

Java / Spring map

  • →

    A Java record makes a perfect immutable memento. Serialization-based snapshots are the heavy version.

Code & diagrams

Memento.javajava

Editor snapshots: save, change, restore.

// Originator
public final class Editor {
  private String text = "";
  private int cursor = 0;

  public void type(String s) { text = text.substring(0, cursor) + s + text.substring(cursor); cursor += s.length(); }

  public Snapshot save() { return new Snapshot(text, cursor); }       // create memento
  public void restore(Snapshot s) { this.text = s.text(); this.cursor = s.cursor(); }

  // Memento: immutable; only Editor knows what the fields mean
  public record Snapshot(String text, int cursor) {}
}

// Caretaker
public final class History {
  private final Deque<Editor.Snapshot> saves = new ArrayDeque<>();
  public void push(Editor.Snapshot s) { saves.push(s); }
  public Editor.Snapshot pop() { return saves.pop(); }
}

// Editor e = new Editor(); History h = new History();
// e.type("Hello");  h.push(e.save());
// e.type(" World"); e.restore(h.pop());   // back to "Hello"

Explain without notes

01

When would you choose Memento over Command for undo, and vice versa?

Practice

01

Add checkpoints to the Tic-Tac-Toe LLD so a player can take back the last move.

Trade-offs

  • ↔

    Full snapshots are simple but use lots of memory for big objects. Keep a cap on history, or store diffs instead.

Completion checklist

  • I can name the three roles and implement save/restore without exposing private fields.

Back to phase