the memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback). the memento pattern is implemented with three objects: the originator, a caretaker and a memento. the originator is some object that has an internal state. the caretaker is going to do something to the originator, but wants to be able to undo the change. the caretaker first asks the originator for a memento object. then it does whatever operation (or sequence of operations) it was going to do. to roll back to the state before the operations, it returns the memento object to the originator. the memento object itself is an opaque object (one which the caretaker cannot, or should not, change). when using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object. classic examples of the memento pattern include the seed of a pseudorandom number generator (it will always produce the same sequence thereafter when initialized with the seed state) and the state in a finite state machine. == java example ==  the following java program illustrates the "undo" usage of the memento pattern. import java.util.list; import java.util.arraylist; class originator { private string state; // the class could also contain additional data that is not part of the // state saved in the memento.. public void set(string state) { system.out.println("originator: setting state to " + state); this.state = state; } public memento savetomemento() { system.out.println("originator: saving to memento."); return new memento(this.state); } public void restorefrommemento(memento memento) { this.state = memento.getsavedstate(); system.out.println("originator: state after restoring from memento: " + state); } public static class memento { private final string state; public memento(string statetosave) { state = statetosave; } public string getsavedstate() { return state; } } } class caretaker { public static void main(string[] args) { list savedstates = new arraylist(); originator originator = new originator(); originator.set("state1"); originator.set("state2"); savedstates.add(originator.savetomemento()); originator.set("state3"); // we can request multiple mementos, and choose which one to roll back to. savedstates.add(originator.savetomemento()); originator.set("state4"); originator.restorefrommemento(savedstates.get(1)); } } the output is: originator: setting state to state1 originator: setting state to state2 originator: saving to memento. originator: setting state to state3 originator: saving to memento. originator: setting state to state4 originator: stat
Software_design_patterns