美文网首页
行为型模式 --- 备忘录模式

行为型模式 --- 备忘录模式

作者: 十二找十三 | 来源:发表于2020-09-06 21:47 被阅读0次
    package study.org;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) {
            Model originator = new Model();
            Storage storage = new Storage();
    
            originator.setValue("State #1"); // first init value
            storage.add(originator.saveStateToMemento());
    
            originator.setValue("State #2");// second init value
            storage.add(originator.saveStateToMemento());
    
            System.out.println("Current State: " + originator.getValue());
            originator.restoreMemento(storage.get(0));
            System.out.println("First saved State: " + originator.getValue());
            originator.restoreMemento(storage.get(1));
            System.out.println("Second saved State: " + originator.getValue());
        }
    }
    
    // 备忘
    class Memento {
        private String state;
    
        public Memento(String state) {
            this.state = state;
        }
    
        public String getState() {
            return state;
        }
    }
    
    // 测试实体类
    class Model {
        private String value;
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    
        public Memento saveStateToMemento() {
            return new Memento(value);
        }
    
        public void restoreMemento(Memento memento) {
            this.value = memento.getState();
        }
    }
    
    // 存储
    class Storage {
        private List<Memento> mementoList = new ArrayList<Memento>();
    
        public void add(Memento state) {
            mementoList.add(state);
        }
    
        public Memento get(int index) {
            return mementoList.get(index);
        }
    }
    

    相关文章

      网友评论

          本文标题:行为型模式 --- 备忘录模式

          本文链接:https://www.haomeiwen.com/subject/dydhektx.html