Memento

Memento

Intent

Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

Also known as

Token

Applicability

Use the memento pattern when:

  • A snapshot of an object's state must be saved so that it can be restored to that state later
  • A direct interface to obtaining the state would expose implementation details and break the object's encapsulation.

Structure

Orange

Participants

  • Memento: stores internal state of the Originator object. The memento may store as much or as little of the state as necesary.Protects against access by objects other than the originator.
  • Originator: creates a memento to containing a snapshot of it's current internal state, usues the memento to restore it's internal state.
  • Caretaker: is responsible for the memento's safekeeping, never operates on or examines the contents of a memento.

Collaborations

  • A caretaker requests a memento from an originator, holds it for a time, and passes it back to the originator.
  • Mmemntoes are passive. Only the originator that created a memento will assign or retrieve it's state.

Consequences

The memento pattern has several consequences:

  • Preserving encapsulation boundaries.
  • It simplifies Originator.
  • Using mementoes might be expensive.
  • Defining narrow and wide interfaces.
  • Hidden costs in caring for mementos.

Sample Code

Memento

Related Patterns

  • Command: Command can use mementos to maintain state for undoable operations.
  • Iterator: Mementos can be used for iteration.