Memento Pattern

This lesson discusses how the state of an object can be exported as a snapshot without exposing the internals of the object.

What is it ?

The literal meaning of memento is an object kept as a reminder or souvenir of a person or an event. The memento pattern let's us capture the internal state of an object without exposing its internal structure so that the object can be restored to this state later. In some sense we are saving a token or a memento of the original object and then recreating the object's state using the memento at a later time.

Details

The object whose state we capture is called the Originator. The originator's snapshot is called the memento. The memento object is held by another object called the Caretaker. The interaction between these three entities happens as follows:

  1. The caretaker requests the originator for a snapshot of its internal state.

  2. The originator produces a memento.

  3. The memento is held by the caretaker and passed back to the originator when required to revert its state to that captured in the memento. If that need doesn't arise, the memento is eventually discarded by the caretaker.

In the absence of the memento pattern, the originator would need to expose its complete internal state to outside classes who can then create snapshots of the internal state of the originator at any time. However, this approach is brittle, breaks ...