博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java学习笔记-设计模式20(备忘录模式)
阅读量:4602 次
发布时间:2019-06-09

本文共 1783 字,大约阅读时间需要 5 分钟。

意图

  在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到保存的状态。

 

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 Storage {            private Memento memento;            public Storage(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("egg");            // 创建备忘录          Storage storage = new Storage(origi.createMemento());            // 修改原始类的状态          System.out.println("初始化状态为:" + origi.getValue());          origi.setValue("niu");          System.out.println("修改后的状态为:" + origi.getValue());            // 回复原始类的状态          origi.restoreMemento(storage.getMemento());          System.out.println("恢复后的状态为:" + origi.getValue());      }  }

  

  转自:http://blog.csdn.net/zhangerqing/article/details/8245537

转载于:https://www.cnblogs.com/gxl00/p/5050595.html

你可能感兴趣的文章
swoolefy PHP的异步、并行、高性能网络通信引擎内置了Http/WebSocket服务器端/客户端...
查看>>
Python学习笔记
查看>>
unshift()与shift()
查看>>
使用 NPOI 、aspose实现execl模板公式计算
查看>>
行为型模式:中介者模式
查看>>
How to Notify Command to evaluate in mvvmlight
查看>>
33. Search in Rotated Sorted Array
查看>>
461. Hamming Distance
查看>>
Python垃圾回收机制详解
查看>>
{面试题1: 赋值运算符函数}
查看>>
Node中没搞明白require和import,你会被坑的很惨
查看>>
Python 标识符
查看>>
Python mysql 创建连接
查看>>
企业化的性能测试简述---如何设计性能测试方案
查看>>
centos7 安装中文编码
查看>>
POJ - 3683 Priest John's Busiest Day
查看>>
正则表达式start(),end(),group()方法
查看>>
vuejs 学习旅程一
查看>>
javascript Date
查看>>
linux常用命令2
查看>>