Memento

Category

Behavioral pattern

Problem

Capture and externalize an object’s internal state so that the object can be restored to this state later, without violating encapsulation. Useful for implementing undo functionality.

Solution

  • Create a Memento object that stores the internal state of the Originator
  • The Originator creates Mementos when needed and restores from them
  • The Caretaker manages Mementos but cannot access or modify their contents

Structure

  • Memento: Stores internal state of the Originator; can be narrow (interface) or wide (full state)
  • Originator: Creates Mementos; can restore from them; knows how to create/restore state
  • Caretaker: Stores Mementos; does not access or modify their contents

Key Benefits

  • Encapsulation preserved — Internal state is captured without exposing implementation details
  • Undo/rollback support — Natural fit for undo functionality and snapshots
  • Decoupled storage — Caretaker doesn’t need to understand the state format

Trade-offs

  • Cost — Creating and storing Mementos can be expensive for large state
  • Resource management — Mementos must be cleaned up when no longer needed

When to Use

  • A snapshot of an object’s internal state is needed to restore it later
  • Directly exposing an object’s internals would violate encapsulation
  • Implementing undo/redo or checkpoint functionality

Examples