Codacoda
Back to Academy

design patterns

Memento

The Memento pattern captures and externalizes an object's internal state without violating encapsulation, so that the object can be restored to this state later. It enables undo mechanisms by saving snapshots of state. The key participants are the Originator (creates a memento containing a snapshot of its current internal state and uses mementos to restore its state), Memento (stores the internal state of the Originator — opaque to other objects), and Caretaker (responsible for the memento's safekeeping but never operates on or examines the contents of a memento). Think of saving a game: the game state is captured at a checkpoint (memento), stored by the save system (caretaker), and the game (originator) can reload from any saved checkpoint. Use Memento when you need to save and restore the state of an object and direct access to the state would expose implementation details.

Use Cases

  • Undo/redo in editors and design tools
  • Game save/load checkpoint systems
  • Transaction rollback in database operations
  • Form state preservation for back/forward navigation

Visualization

storesrestore fromOriginator-state+save()+restore()Memento-state+getState()Caretaker-history[]+undo()State Snapshotfield1field2
Speed:1x
Memento — captures and externalizes an object's internal state for later restorationStep 1 / 7

Implementation

Output

Click "Run Code" to see output...