设计模式-备忘录模式

来源:互联网 发布:手机全局透明软件 编辑:程序博客网 时间:2024/06/07 22:37
备忘录模式(Memento Pattern)
在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

涉及角色:
1.Original(发起人):负责创建一个备忘录Memento,用以记录当前时刻自身的内部状态,并可使用备忘录恢复内部状态。Originator可以根据需要决定Memento存储自己的哪些内部状态。
2.Memento(备忘录):负责存储Originator对象的内部状态,并可以防止Originator以外的其他对象访问备忘录。备忘录有两个接口:Caretaker只能看到备忘录的窄接口,他只能将备忘录传递给其他对象。Originator却可看到备忘录的宽接口,允许它访问返回到先前状态所需要的所有数据。
3.Caretaker(管理者):负责备忘录Memento,不能对Memento的内容进行访问或者操作。

public class Original{            private String value;            public String getValue() {          return value;      }        public void setValue(String value) {          this.value = value;      }        public Original(String value) {          this.value = value;      }        public Memento createMemento(){          return new Memento(value);      }            public void restoreMemento(Memento memento){          this.value = memento.getValue();      }  }


public class Memento {            private String value;        public Memento(String value) {          this.value = value;      }        public String getValue() {          return value;      }        public void setValue(String value) {          this.value = value;      }  }


public class Caretaker{            private Memento memento;            public Caretaker(Memento memento) {          this.memento = memento;      }        public Memento getMemento() {          return memento;      }        public void setMemento(Memento memento) {          this.memento = memento;      }  }


测试类
public class Test {        public static void main(String[] args) {         // 创建发起人          Original origi = new Original("1");          // 创建备忘录          Caretaker caretaker = new Storage(origi.createMemento());            // 修改原始类的状态          System.out.println("初始化状态为:" + origi.getValue());          origi.setValue("2");          System.out.println("修改后的状态为:" + origi.getValue());            // 回复原始类的状态          origi.restoreMemento(caretaker.getMemento());          System.out.println("恢复后的状态为:" + origi.getValue());      }  }


测试结果
初始化状态为:1修改后的状态为:2恢复后的状态为:1
0 0