Many times we face a situation where we need to store the state of an object. One of the best examples is rollback operation where we need to restore the application to some previous state. This can be achieved by creating a copy of the object at certain point of time while working on the actual object. The actual object stores the list of own objects as a state. The object can be restored to some previous state through the list of objects. This approach is memory intensive as we keep a copy of the object at the defined states. The other drawback is violation of encapsulation in order to store the state of an object as we have to expose the internal state of an object such as member variables. Also, if we are interested only in some part of an object to be stored, we store the whole object, which is not required.
Memento pattern is one the GOF design pattern that comes as a rescue to store the state of an object. Memento means a reminder of past events or a souvenir. In Memento pattern, we do not create a copy of an object. We create Mementos that hold the state of an object and it might include full object or elements of an object that needs to be stored.
Wikipedia definition of Memento Pattern
The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).
Ingredients of a Memento Pattern
Originator: It is the one whose state needs to be saved and creates the Memento object.
Memento: It holds the internal state of an Originator.
Caretaker: It is responsible for keeping the memento.
In order to save the state of an Originator, Caretaker asks the originator to create and pass the memento. The originator saves the internal state and passes the memento to the CareTaker. Caretaker maintains the memento. Whenever, Originator needs to be restored to a previous state, CareTaker calls the SetMemento of Originator and passes the saved memento. The originator accepts the memento and restores the originator to previous state.
Let’s take an example of an Employee whose state needs to be stored, and restored to a previous state.
Read more: Codeproject