JAVA的23种设计模式-----备忘录模式(一)

备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象回复到原先保存的的状态.
注:
a:备忘录模式就是一个对象的备份模式,提供了一种程序数据的备份方法.
b:备忘录模式包含了发起人角色,备忘录角色,备忘录管理人角色三种角色
c:常见的数据库的事务管理,回滚,用到了备忘录模式.
d:备忘录一旦被创建出来,我们要主动管理其生命周期,建立就要使用,不使用就立即删除其引用,另外,不要在频繁建立备份的场景中使用备忘录模式.
普通的

package MemoOne;
//程序员
public class Programer {
//代码状态
    private String codeState = null;
    //代码状态变更
    public void changCodeState(){
        this.codeState="代码被修改过了";
    }
    //getter/setter
    public String getCodeState() {
        return codeState;
    }
    public void setCodeState(String codeState) {
        this.codeState = codeState;
    }
    //保留一个备份
    public Memento createMemento(){
        return new Memento(this.codeState);
    }
    //恢复备份代码
    public void restoreMemento(Memento _mement){
        this.setCodeState(_mement.getCodeState());
    }
package MemoOne;

//备忘录
/**
 * @author lanou3g
 *
 */
public class Memento {
    // 代码状态
    private String codeState = null;
    // 构造函数
    public Memento(String codeState) {
        this.codeState = codeState;
    }
    //getter,getter
    public String getCodeState() {
        return codeState;
    }
    public void setCodeState(String CodeState) {
        this.codeState = codeState;
    }

}

package MemoOne;
//备忘录管理者
public class Caretaker {
//备忘录对象
    private Memento memento;
    //getter.setter

    public Memento getMemento() {
        return memento;
    }

    public void setMemento(Memento memento) {
        this.memento = memento;
    }
    
}

package MemoOne;
//备忘录恢复场景模拟
public class Client {
public static void main(String[] args) {
    //程序员出场
    Programer programer = new Programer();
    //备份管理者出场
    Caretaker caretaker = new Caretaker();
    //初始化代码状态
    programer.setCodeState("项目代码已经完成了");
    //输入:项目代码已经完成了
    System.out.println(programer.getCodeState());
    //代码备份
    caretaker.setMemento(programer.createMemento());
    //代码变更
    programer.createMemento();
    System.out.println(programer.getCodeState());
    //输出:代码被修改过了
    //代码按照备份恢复
    programer.restoreMemento(caretaker.getMemento());
    System.out.println(programer.getCodeState());
    //输入:项目代码已经完成了
}
}



}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容