zoukankan      html  css  js  c++  java
  • java学习笔记-设计模式20(备忘录模式)

    意图

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

    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

  • 相关阅读:
    Phpstudy升级到Mysql8
    PHP 匿名函数使用技巧
    PHP 中的CURL 模拟表单的post提交
    Go中局部全局变量的区分
    Php中的goto用法
    struct的匿名用法详解
    Go中多个返回值的技巧
    C# 多线程之List的线程安全问题
    C# 多线程七之Parallel
    C# 多线程六之Task(任务)三之任务工厂
  • 原文地址:https://www.cnblogs.com/gxl00/p/5050595.html
Copyright © 2011-2022 走看看