zoukankan      html  css  js  c++  java
  • 设计模式之 备忘录模式

    备忘录模式 将当前对象的内部状态保存到备忘录中,以便在需要时能将改对象的状态恢复到原先保存的状态。

    image

    (1)定义备忘录

    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;
        }
    }

    (2)定义原始数据

    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();
        }
    }

    (3)定义备忘录管理者

    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;
        }
    }

    (4)使用备忘录模式

    public static void main(String[] args){
        Original original = new Original("张三");
        Storage storage = new Storage(original.createMemento());
        // 修改状态
        original.setValue("李四");
        // 恢复至原状态
        original.restoreMemento(storage.getMemento());
    }

  • 相关阅读:
    python day6
    python day5
    python基础晋级篇
    python基础篇
    初识Python
    if语句
    A22. openstack架构实战-openstack的api
    A21. openstack架构实战-配置三层网络vxlan
    A20. openstack架构实战-虚拟机创建的流程
    A19. openstack架构实战-云主机的冷迁移
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15238927.html
Copyright © 2011-2022 走看看