==> Engine.java <== //http://www.moviemalls.com/M/memento.htm /** * This does the computations and furnishes and uses Mementos for undoes. *
Memento Design Pattern example for COM1204 Summer 2003. * * @author Bob Futrelle * @version 0.1, 4 July 2003 * */ public class Engine { private int result; // initially zero int getResult() { return result; } void postResult(){ System.out.println("Result now = " + result); } void times(int factor) { result *= factor; postResult(); } void add(int summand) { result += summand; postResult(); } Memento getMemo() { return new Memento(); } void reset(Object m) { result = ((Memento)m).savedResult; } // reset // Here's the trick, a private class only Engine can produce and use. private class Memento { private int savedResult; private Memento() { savedResult = result; } } } // class Engine ==> MementoTest.java <== //http://www.moviemalls.com/M/memento.htm /** * This tests Memento and handles the state push and pop itself * So consider this the application (a separate one could have been constructed). *
Memento Design Pattern example for COM1204 Summer 2003. * * @author Bob Futrelle * @version 0.1, 4 July 2003 * */ public class MementoTest { public static void main(String[] args) { StateStore states = new StateStore(); Engine eng = new Engine(); eng.postResult(); eng.add(7); // 7 states.addMemo(eng); // 7 eng.times(5); // 35 eng.add(4); states.addMemo(eng); // 39 eng.add(1); // 40 states.redoMemo(eng); // 39 states.redoMemo(eng); // 7 states.redoMemo(eng); // no more states.redoMemo(eng); // no more } // main() } // class Engine ==> StateStore.java <== import java.util.*; //http://www.moviemalls.com/M/memento.htm /** * This obeys the Stack protocol and is used for storing and retrieving Mementos. *
Memento Design Pattern example for COM1204 Summer 2003. * * @author Bob Futrelle * @version 0.1, 4 July 2003 * */ public class StateStore extends Stack{ void addMemo(Engine eng) { push(eng.getMemo()); System.out.println("Saving state " + eng.getResult()); } void redoMemo(Engine eng) { if(!empty()) { eng.reset(pop()); System.out.println("State restored to " + eng.getResult()); } else System.out.println("No more saved states."); } } // class StateStore