//这个是要保存的状态 private int state= 90; //保持一个“备忘录管理者角色”的对象 private Caretaker c = new Caretaker(); //读取备忘录角色以恢复以前的状态 public void setMemento(){ Memento memento = (Memento)c.getMemento(); state = memento.getState(); System.out.println("the state is "+state+" now"); } //创建一个备忘录角色,并将当前状态属性存入,托给“备忘录管理者角色”存放。
public void createMemento(){ c.saveMemento(new Memento(state)); } //this is other business methods... //they maybe modify the attribute state
public void modifyState4Test(int m){ state = m; System.out.println("the state is "+state+" now"); }
private class Memento implements MementoIF{ private int state ; private Memento(int state){ this.state = state ; }
private int getState(){ return state; } } }
//测试代码——客户程序
public class TestInnerClass{ public static void main(String[] args){ Originator o = new Originator(); o.createMemento(); o.modifyState4Test(80); o.setMemento(); } }
//窄接口
interface MementoIF{}
//“备忘录管理者角色”
class Caretaker{ private MementoIF m ; public void saveMemento(MementoIF m){ this.m = m; } public MementoIF getMemento(){ return m; } }