Memento Pattern

The state of an object can be defined as the values of its properties or attributes at any given point of time. The Memento pattern is useful for designing a
mechanism to capture and store the state of an object so that the object can be put back to this previous state if needed; Like an undo operation.

The object whose state needs to be captured is referred to as Originator. The Originator stores all those attributes that are required for restoring its state in a separate object referred to as Memento. Also Memento does not expose the object’s internal structure. Memento is usually implemented as an inner class of Originator.

There is another object involved called Caretaker or Memento Handler. The Caretaker can ask the originator for a memento object and can roll back.

When the client wants to restore the Originator back to its previous state, it simply passes a Memento back to the Originator using the Caretaker.

memento.jpeg
class Originator {
    private Object state; //the state we want to keep
 
     public void saveToMemento() { 
        //save the current state to a memento
            new Memento().saveState(state); 
    }
 
    public void restoreFromMemento(Object memento) {
            state = memento.getSavedState(); 
    }
 
    //inner class
    private static class Memento {
            private Object state;
        public void saveState(Object theState) { state = theState; }
        public Object getSavedState() { return state; }
    }
}
 
class Caretaker {
    private List<Object> savedStates = new ArrayList<Object>();
 
    public void addMemento(Object m) { savedStates.add(m); }
    public Object getMemento(int index) { return savedStates.get(index); }
}   
 
class Cliente {
    public static void main(String[] args) {
        Caretaker caretaker = new Caretaker();
 
        Originator originator = new Originator();
        originator.set("State1");
        caretaker.addMemento( originator.saveToMemento() );
        originator.set("State2"); // chaging the state of originator
        caretaker.addMemento( originator.saveToMemento() );
    //putting the state back
        originator.restoreFromMemento( caretaker.getMemento(1) );
    }
}
page_revision: 9, last_edited: 1219831660|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License