Memento

Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. Use when a snapshot of an object's state must be saved for later restoration and a direct interface to that state would expose implementation details.

Examples:

  • A text editor needs undo. Before each operation, the editor asks the document to produce a Memento — an opaque snapshot of its state. The snapshots are stored in a history stack. On undo, the editor hands the latest memento back to the document, which restores itself without any external code ever accessing its private fields.
class Memento {
  State state;
public:
  Memento(State s) : state(s) {}
  State GetState() const { return state; }
};
class Originator {
  State state;
public:
  Memento* CreateMemento() { return new Memento(state); }
  void SetMemento(Memento* m) { state = m->GetState(); }
};
class Caretaker { Memento* saved; };

Synonyms: token, snapshot