美文网首页
设计模式-备忘录模式

设计模式-备忘录模式

作者: IAmWhoAmI | 来源:发表于2016-07-28 09:38 被阅读10次

    临时存储。也算一种模式?

    class Originator{
        private String state="";
    
        public String getState(){
            return state;
        }
    
        public void setState(String state) {
            this.state = state;
        }
        public Memento createMemento(){
            return new Memento(this.state);
        }
        public void restoreMemento(Memento memento){
            this.setState(memento.getState());
        }
    
    }
    class Memento{
        private String state="";
        public Memento(String state){
            this.state = state;
        }
    
        public String getState() {
            return state;
        }
    
        public void setState(String state) {
            this.state = state;
        }
    }
    
    class Caretaker{
        private Memento memento;
        public Memento getMemento(){
            return memento;
        }
    
        public void setMemento(Memento memento) {
            this.memento = memento;
        }
    }
    
    public class MementoTest {
        public static void main(String[] args){
            Originator originator = new Originator();
            originator.setState("state1");
            System.out.println("initial state:"+originator.getState());
    
            Caretaker caretaker = new Caretaker();
            caretaker.setMemento(originator.createMemento());
    
            originator.setState("state2");
            System.out.println("change State:"+originator.getState());
            originator.restoreMemento(caretaker.getMemento());
            System.out.println("back:"+originator.getState());
        }
    }
    

    相关文章

      网友评论

          本文标题:设计模式-备忘录模式

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