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

  • 相关阅读:
    how to pass a Javabean to server In Model2 architecture.
    What is the Web Appliation Archive, abbreviation is "WAR"
    Understaning Javascript OO
    Genetic Fraud
    poj 3211 Washing Clothes
    poj 2385 Apple Catching
    Magic Star
    关于memset的用法几点
    c++ 函数
    zoj 2972 Hurdles of 110m
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15238927.html
Copyright © 2011-2022 走看看