306备忘录模式

82 阅读1分钟

定义

备忘录是一种行为设计模式,允许在不暴露对象实现细节的情况下保存和回复对象之前的状态

类图

图片1.png

代码

public class MementoPattern {
    public static void main(String[] args) {
        History history = new History();
        Document document = new Document();
        document.change("abc");
        history.add(document.save());
        document.change("def");
        history.add(document.save());
        document.change("ghi");
        history.add(document.save());
        document.change("lmn");
        document.resume(history.getLastVersion());
        document.print();
        document.resume(history.getLastVersion());
        document.print();
    }
}
class Document{
    private String content; //备份
     public BackUp save(){
         return new BackUp(content);
     }
     public void resume(BackUp backUp){
         content = backUp.content;
     }
     public void change(String content){
         this.content =content;
     }
     public void print(){
         System.out.println(content);
     }
}
// 备忘录接口
interface Memento{}
// 备忘录类
class BackUp implements Memento{
    String content;
    public BackUp(String content){
        this.content =content;
    }
}
//备忘录栈
class History{
    Stack<BackUp> backUpStack = new Stack<>();
    public void add(BackUp backup){
        backUpStack.add(backup);
    }
    public BackUp getLastVersion(){
        return backUpStack.pop();
    }
}