java 制作备忘录_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());

//输入:项目代码已经完成了

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值