RecapDifficulty: Advanced1 min

Recap: Memento Pattern

The originator saves and restores itself, and the caretaker holds snapshots it cannot read.

Memento saves an object's state for later without making that state public.

  • Intent. Capture an object's internal state so it can be restored, without breaking encapsulation.
  • Participants. The originator makes and reads mementos; the memento holds the state; the caretaker keeps mementos and never reads them.
  • Sealing it. A nested class with private fields in Java, a #private field in TypeScript, a leading underscore by convention in Python.
  • Copy, do not share. A memento must copy mutable state, or it changes with the originator.
  • Against Command. A command undoes by reversing its change; a memento undoes by copying the old state back.
  • The trap. Full snapshots on every change fill the memory; cap the history or store only the changes.
  • When not. Large state that changes constantly, or state that cannot be copied back.