GoF Definition: Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.
Our aim is to save the state of an object, so that in the future, we can go back to the specified state. Three objects are playing the game here—a memento, a caretaker, and the originator. The memento will store the internal states of the originator. The originator can have the internal states and it has the ability to restore into its earlier state. An originator can also retrieve information from the memento. The caretaker takes care of the memento’s safekeeping or protection and it should not examine the contents of the memento.
In notepad we use undo frequently by pressing ctrl+Z.
A classic example in this category includes the state in a finite state machine. Apart from this, in real-world database programming, often we may need to roll back a transaction operation.
Please go through the code. Use the comments for your ready reference. Please also note that if you are familiar with C#, you can also use C# properties in place of the getter and setter operations used here.
High-level structure of the parts of the program is as follows:
package memento.pattern.demo;
// Memento class
class Memento
{
private String state;
public Memento(String state)
{
this.state = state;
}
public String getState()
{
return state;
}
}
// Originator class
class Originator
{
private String state;
Memento m;
public void setState(String state)
{
this.state = state;
System.out.println("State at present : " +state);
}
// Creates memento
public Memento OriginatorMemento()
{
m = new Memento(state);
return m;
}
// Back to old state
public void Revert(Memento memento)
{
System.out.println("Restoring to previous state...");
state = memento.getState();
System.out.println("State at present :" +state);
}
}
//Caretaker Class
class Caretaker
{
private Memento _memento;
public void SaveMemento(Memento m)
{
_memento = m;
}
public Memento RetrieveMemento()
{
return _memento;
}
}
class MementoPatternEx
{
public static void main(String[] args)
{
System.out.println("***Memento Pattern Demo*** ");
Originator o = new Originator();
o.setState("First state");
// Holding old state
Caretaker c = new Caretaker();
c.SaveMemento(o.OriginatorMemento());
//Changing state
o.setState("Second state");
// Restore saved state
o.Revert(c.RetrieveMemento());
}
}