Let's suppose if you are going to any function like a birthday party or marriage, you will buy some gift for that person. If that person sees that gift after five years, it could remind your presence for that function. So here the gift is acting as a memento.
Let's consider a bank example. If your bank debits some amount mistakenly, you would call your bank and conveys your query. The bank checks your transaction and if the operation was done by mistake they bank would return you the debited amount. Here, the bank is rollbacking your transaction by changing the state to the previous state.
Let's consider a technical example. We would have been using word editors like Microsoft Word. There is a feature called "undo". You can go to previous states by just clicking undo option.
public class Memento
{
private String state;
public Memento(String state)
{
this.state = state;
}
public String getState()
{
return state;
}
}
public class Originator
{
private String state;
public void setState(String state)
{
this.state = state;
}
public String getState()
{
return state;
}
public Memento saveStateToMemento()
{
return new Memento(state);
}
public void getStateFromMemento(Memento memento)
{
state = memento.getState();
}
}
public class CareTaker
{
private List<Memento> mementoList = new ArrayList<>();
public void add(Memento state)
{
mementoList.add(state);
}
public Memento get(int index)
{
return mementoList.get(index);
}
}
public class MementoDemo
{
public static void main(String[] args)
{
Originator originator = new Originator();
CareTaker careTaker = new CareTaker();
originator.setState("State 1");
originator.setState("State 2");
careTaker.add(originator.saveStateToMemento());
originator.setState("State 3");
careTaker.add(originator.saveStateToMemento());
originator.setState("State 4");
System.out.println("Current State: " + originator.getState());
originator.getStateFromMemento(careTaker.get(0));
System.out.println("First saved State: " + originator.getState());
originator.getStateFromMemento(careTaker.get(1));
System.out.println("Second saved State: " + originator.getState());
}
}
For tutorial videos, please check out the premium Software Design Pattern course on Udemy.