Memento pattern
The Memento Pattern is used to store the Record of the Internal state of object and encapsulate it and reclaim it without information of the original object.
Benefit and use of Memento
-
Record the Information for reclaim the object later.
-
It have the Need undo/redo features.
-
It is Used basically in database transaction.
Example
package r4r;
import java.util.*;
class Memento {
private String state;
public Memento(String Save) { state = Save; }
public String getSavedState() { return state; }
}
class Origin {
private String state;
public void set(String state) {
System.out.println("Origin: Setting state to "+state);
this.state = state;
}
public Memento MementoSave() {
System.out.println("Origin: Save to the Memento.");
return new Memento(state);
}
public void recoverFromMemento(Memento me) {
state = me.getSavedState();
System.out.println("Origin: State after
recovering from Memento: "+state);
}
}
class Landlord {
private ArrayList<Memento> savedStates = new ArrayList<Memento>();
public void addMemento(Memento m) { savedStates.add(m); }
public Memento getMemento(int index)
{ return savedStates.get(index); }
}
public class mementotest1 {
public static void main(String[] args) {
Landlord ll = new Landlord();
Origin o1 = new Origin();
o1.set("State1");
o1.set("State2");
ll.addMemento( o1.MementoSave() );
o1.set("State3");
ll.addMemento( o1.MementoSave() );
o1.set("State4");
o1.recoverFromMemento( ll.getMemento(1) );
}
}