Memento Pattern
Explore the Memento pattern to understand how it captures an object's internal state without exposing its details, allowing restoration at a later point. This lesson helps you learn about the roles of Originator, Memento, and Caretaker, and how this pattern preserves encapsulation while enabling state rollback in software development.
We'll cover the following...
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:
The caretaker requests the originator for a snapshot of its internal state.
The originator produces a memento.
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 ...