Memento

Capture an object's state in a snapshot so you can restore it later, without exposing the object's internals to whoever keeps the snapshots.

Description

Memento splits undo into three roles. The originator (an editor) owns its state and can produce a snapshot of it or restore from one. The memento is that snapshot: immutable and opaque to everyone else. The caretaker (a history) stores mementos and hands them back, but never looks inside.

The result is undo without leaking internals: the history doesn't know what an editor's state contains, and the editor doesn't manage a history. It's also simpler than writing an exact inverse for every operation, because restoring a snapshot always works.

Class diagram

keeps«create»History- snapshots: EditorSnapshot[]- limit: number+ push(s)+ pop(): EditorSnapshotEditorSnapshot+ text, cursor+ createdAtEditor- text: string- cursor: number+ type(words)+ save(): EditorSnapshot+ restore(snapshot)

Memento pattern class diagram

  1. Class History with + push(s), + pop(): EditorSnapshot.
  2. Class EditorSnapshot.
  3. Class Editor with + type(words), + save(): EditorSnapshot, + restore(snapshot).
  4. History keeps EditorSnapshot.
  5. Editor creates EditorSnapshot.

Sequence diagram

AppEditorHistory1. save()2. snapshot3. push(snapshot)4. type(" Pizza is on me!!!")5. pop()6. last snapshot7. restore(snapshot)

Memento pattern sequence diagram

  1. App → Editor: save().
  2. App receives "snapshot" back from Editor.
  3. App → History: push(snapshot).
  4. App → Editor: type(" Pizza is on me!!!").
  5. App → History: pop().
  6. App receives "last snapshot" back from History.
  7. App → Editor: restore(snapshot).

TypeScript example

An editor that saves frozen snapshots of its text and cursor. The history caps how many it keeps and never looks inside them.

memento.ts
// Memento: an editor saves snapshots of its state so it can go back,
// without exposing its internals to the history.

// Memento: an opaque, immutable snapshot
class EditorSnapshot {
  readonly createdAt: number;
  // only the editor reads these (by convention; TS #private fields would enforce it)
  readonly text: string;
  readonly cursor: number;
  constructor(text: string, cursor: number, createdAt: number) {
    this.text = text;
    this.cursor = cursor;
    this.createdAt = createdAt;
  }
}

// Originator: owns the state and knows how to save and restore it
class Editor {
  private text = "";
  private cursor = 0;

  type(words: string): void {
    this.text = this.text.slice(0, this.cursor) + words + this.text.slice(this.cursor);
    this.cursor += words.length;
  }

  save(at: number): EditorSnapshot {
    return Object.freeze(new EditorSnapshot(this.text, this.cursor, at));
  }

  restore(snapshot: EditorSnapshot): void {
    this.text = snapshot.text;
    this.cursor = snapshot.cursor;
  }

  get content(): string {
    return this.text;
  }
}

// Caretaker: keeps snapshots, never looks inside them
class History {
  private readonly snapshots: EditorSnapshot[] = [];
  private readonly limit: number;
  constructor(limit: number) {
    this.limit = limit;
  }
  push(s: EditorSnapshot): void {
    this.snapshots.push(s);
    if (this.snapshots.length > this.limit) this.snapshots.shift(); // cap memory use
  }
  pop(): EditorSnapshot | undefined {
    return this.snapshots.pop();
  }
}

export function demo(): string[] {
  const editor = new Editor();
  const history = new History(50);

  editor.type("Dear team,");
  history.push(editor.save(1));
  editor.type(" the release is on Friday.");
  history.push(editor.save(2));
  editor.type(" Pizza is on me!!!");

  const lines = [`now:  ${editor.content}`];
  editor.restore(history.pop()!);
  lines.push(`undo: ${editor.content}`);
  editor.restore(history.pop()!);
  lines.push(`undo: ${editor.content}`);
  return lines;
}

When to use it

Use it when

  • You need undo, "revert to saved", checkpoints or drafts.
  • Writing an inverse for every operation would be hard or error-prone, but saving the state is easy.
  • You want to try something risky (a what-if calculation, a migration step) and roll back if it fails.
  • The object's internals should stay private even though something else manages its history.

Avoid it when

  • The state is very large and changes in small steps. Full snapshots cost too much memory; store diffs or use Command with inverse operations.
  • The state includes things you can't copy meaningfully: open connections, timers, external side effects.
  • Undo must also reverse effects outside the object, such as emails sent or payments made. Snapshots can't un-send.

Pitfalls

  • Unbounded history eating memory. Cap the number of snapshots or store compressed diffs.
  • Shallow snapshots that share mutable arrays or objects with the live state, so the "snapshot" changes too. Copy deeply or use immutable data.
  • Snapshots that outlive a schema change. If you persist mementos, version them.

Alternatives

Command

Choose it when each action has a clean inverse and state is too big to snapshot.

Prototype

Choose it when you copy objects to create new ones, not to go back in time.

Event Sourcing

Choose it when you want the full history of a system's changes stored durably, not in-memory undo.

Immutable state

Choose it when your state is already immutable (as in many UI stores); keeping old references is the snapshot.