Memento Pattern in Java

The concept of this pattern borrows from the meaning of a memento that is normally a remembrance of someone or something from the past. This pattern falls behavioural design patterns as it plays a crucial role in manipulating or changing the state of an object at a certain time. The Memento pattern works towards restoring the previous state of an object after a few changes have been done that have given the object a new shape that is not favourable.

As you carry forward your program/project, you might want to take a few snaps of the state of the components such that in the event of any future error, this version of the application will always remain handy. The Memento Pattern allows you to do just that.

Definition

As per the Gang of Four book, ‘The Memento Pattern is used to restore the state of an object to a previous one.’

Structure of the Memento Pattern

  • Originator – the state of the originator object is the one that needs to be saved. This is the state that the memento object will fall back to in the future.
  • Memento – The current object that will take the state of the originator.
  • Caretaker – The caretaker object triggers the entire process of state restoration.

Example and Code Illustration

We will be developing a text editor that will restore the object to it’s previous state if require by using the memento pattern

//Memento Class
public class TextEdit {
private final String lastState;
public EditMem(String obj) {
lastState = obj;
}
public void returnState(){
System.out.println(“Returned to Previous State”);
}
}

//Originator Class

public class orig{
public String flag;
public void setState(String obj) {
this.flag = obj;
}

public TextEdit store() {
return new TextEdit (flag);
}
public void restore(TextEditor edit)
flag = edit.returnState();                                               //Will take the object back to the saved state
}
}

When to use the Memento Pattern

This behavioural design pattern is put to best use when situations arise where an object has reached a dead-end or some undoable action. To give the object a fresh start, it can be brought back to the state of the originator (reference state as saved). Although this process gives objects many lives, the pattern at times uses up a lot of memory in order to save previous states.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.