“You can’t undo the past… but you can certainly not repeat it.” — Bruce Willis
What is Memento Design Pattern?
When dealing with software applications sometimes it is necessary to do the undo and redo or reverse back a process. This is a type of change of state. if we think this from an OOP approach what the Memento Design Pattern does is that externalize an object’s state into another object and change it accordingly to the previous state or existed state.
There are few main objects when dealing with Memento Design Pattern.
Originator - These classes' state needs to tracked and saved for later use.
Memento - Memento object is where the state is stored, since it stores the state of the Originator class the attributes should be the same as the originator. and the attributes in the memento should be only accessible by the originator.
Care Taker - When an originator object changes to a previous state Care-Taker object is the one that keeps the track of these originators. when the state needs to be changed Care-Taker is the class to call.
Implementation of the Memento Design Pattern
First, we define the “Originator” class, and also the Memento class for managing the state.
Next, we create the “Care-Taker” object for saving and reverting state, because the Memento and originator do not deal directly, because of this “Care-Taker” act as a safeguard.
Care-Taker uses the Stack (FILO (First-in-Last-Out) ) data structure for saving and returning the state. it stores the state as a completely new set rather than adding only new elements to the existing elements (LinkedHashSet in this scenario).
Now let's try executing the program like below,
First, it creates a CareTaker object and the Originator(UserPreferences) object. This example is about storing User preferred movie categories. as the first step, we add two movie categories and save the state. Now the state will look like this.
Now we add another two elements and save them as the current state.
As above it’s a completely new state. And once we need to get the current state. what we will get is the state that we’ve recently saved. in case the developer requests the “revertState()” at the same moment after saving the state. the method will return the set of elements on the top. (Documentary, Horror, Crime, Thriller). and again if called the “revertState()” method without calling saving again it will return the next top set of elements(Documentary, Horror). It always follows First-in-Last-Out Mechanism.
For more information and Hands-on development, video follow the link in the references below.
Complete Source code available here.