The Memento Pattern: Capturing and Restoring State Without Breaking Encapsulation

2026-05-10

You need undo functionality. Or a checkpoint system. Or the ability to roll back a transaction-like operation in memory. The naive approach is to expose every field on your object so the caller can copy them out and stuff them back in later. Congratulations, you've just turned your carefully encapsulated object into a public bag of fields.

The Memento Pattern solves this with three roles:

Real-world example: a text editor's undo stack. Imagine a Document with private content, cursor, and selection fields. Every time the user types, you call document.save() which returns a DocumentMemento. The editor pushes it onto an undo stack. On Ctrl+Z, you pop and call document.restore(memento). The undo manager never sees the cursor offset or selection range — it just shuffles opaque tokens.

class Document {
  private content: string;
  private cursor: number;

  save(): Memento {
    return new Memento(this.content, this.cursor);
  }
  restore(m: Memento) {
    this.content = m.getContent();
    this.cursor = m.getCursor();
  }
}

The memento's getters are package-private (or use a friend class, or a closure) so only the originator can read them. Outside code holds the reference but can't inspect it.

Rule of thumb for memory: if your state is N bytes and you keep K undo steps, you're using N × K bytes. A 50KB document with 100 undo steps is 5MB — fine. A 500MB image buffer with 100 steps is 50GB — not fine. When N is large, switch to command-pattern undo (store the inverse operation) or delta mementos (store only what changed).

When to reach for it:

When to skip it: if the state is trivially copyable and encapsulation isn't a concern (e.g., a value object that's already immutable), just clone it. The Memento pattern earns its complexity when the originator has private invariants that outside code shouldn't touch.

See it in action: Check out Unlocking the Power of the Memento Design Pattern by Sajjad Ali Kh to see this theory applied.
Key Takeaway: Memento lets you snapshot and restore an object's state without exposing its internals — perfect for undo stacks, but watch the memory math when state is large.

All newsletters