Memento pattern is one of the behavioral design patterns. Memento design pattern is used when we want to save the state of an object so that we can restore later on. Memento pattern is used to implement this in such a way that the saved state data of the object is not accessible outside of the object; this protects the integrity of saved state data.
Memento pattern is implemented with two objects – Originator and Caretaker. Originator is the object whose state needs to be saved and restored and it uses an inner class to save the state of Object. The inner class is called Memento and its private, so that it can’t be accessed from other objects.
Caretaker is the helper class that is responsible for storing and restoring the Originator’s state through Memento object. Since Memento is private to Originator, Caretaker can’t access it and it’s stored as an Object within the caretaker.
One of the best real life examples is the text editors where we can save its data anytime and use undo to restore it to previous saved state. We will implement the same feature and provide a utility where we can write and save contents to a File anytime and we can restore it to last saved state. For simplicity, I will not use any IO operations to write data into file.
When to use the Memento Pattern:
Use the Memento Pattern in the following cases:
- 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 would expose implementation details and break the object’s encapsulation
Memento Pattern in JDK: