Memento

Intent

  • Capture and externalize an object’s internal state so that the object can be restored to this state later

  • Without violating encapsulation

Motivation

  • Sometimes, it is necessary to save the state of an object and then restore it later

  • However, objects often encapsulate their state, making it inaccessible to other objects

Applicability

Use the Memento pattern when
  • A snapshot of (some portion of) an object’s state must be saved so that it can be restored to that state later, and

  • A direct interface to obtaining the state (i.e. accessing private fields) would expose implementation details and break encapsulation

Structure

Diagram

Participants

  • Memento

    • Stores internal state of the Originator object.

    • Protects against access by objects other than the originator.

    • Originator

    • Creates a memento containing a snapshot of its current internal state.

    • Uses the memento to restore its internal state.

  • Caretaker

    • Is responsible for the memento’s safekeeping.

    • Never operates on or examines the contents of a memento.

Interactions

Save Memento
Figure 1. Save Memento

Interactions

Restore Memento
Figure 2. Restore Memento

Mementos are passive. Only the originator that created a memento will assign or retrieve its state.

Consequences

  1. Preserves encapsulation boundaries

  2. Simplifies Originator

  3. Mementos might be expensive

  4. Defining narrow and wide interfaces for the Memento may be difficult in some languages

  5. Hidden costs in caring for mementos (number of mementos is unknown)

Trade-offs

  • Use C++ friends to implement narrow/wide interfaces for Memento

  • Store incremental changes instead of snapshots