备忘录模式
基本介绍:
- 备忘录模式在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态
- 可以这样理解备忘录模式:现实生活中的备忘录是用来记录某些要去做的事情,或者是记录已经达成的共同遇见的事情,以防忘记。而在软件层面,备忘录模式有着相同的意义,备忘录对象主要用来记录一个对象的某种状态,或者某些数据,当要做回退时,可以从备忘录对象里获取原来的数据进行恢复操作
- 备忘录模式属于行为型模式
原理类图:
角色说明:
- originator :需要保存状态的对象
- Memento :备忘录对象,负责保存好记录,即originator内部状态
- CareTaker:守护者对象,负责保存多个备忘录对象,使用集合管理,提高效率
- 说明:如果需要保存多个originator对象的不同时间的状态,也可以只需要改变Caretaker中的集合类型
案例:
游戏角色有攻击力和防御力,在大战Boss前保存自身的状态,大战后体力下降,然后从备忘录对象恢复到大战前状态
/**
* 备忘录角色
*/
public class Memento {
private int vit;
private int def;
public Memento(int vit, int def) {
this.vit = vit;
this.def = def;
}
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
}
/**
* 源对象状态
*/
public class GameRole {
private int vit;
private int def;
//创建memento,即根据当前的状态得到memento
public Memento createMemento(){
return new Memento(vit,def);
}
public void recoverFromMemento(Memento memento){
this.vit = memento.getVit();
this.def = memento.getDef();
}
public void display(){
System.out.println("游戏角色当前的防御力 " + this.def + "攻击力:" + this.vit);
}
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
}
/**
* 守护者对象,保存游戏角色状态
* 这里是保存一个
*/
public class Caretaker {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
public class Client {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
GameRole gameRole = new GameRole();
gameRole.setDef(100);
gameRole.setVit(100);
System.out.println("大战Boss之前的状态");
gameRole.display();
caretaker.setMemento(gameRole.createMemento());
System.out.println("大战Boss之后的状态");
gameRole.setVit(50);
gameRole.setDef(50);
gameRole.display();
System.out.println("状态恢复。。。后");
gameRole.recoverFromMemento(caretaker.getMemento());
gameRole.display();
}
}
备忘录模式注意事项和细节:
- 给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便的回到某个历史状态
- 实现了信息的封装,使得用户不需要关心状态的保存细节
- 如果类的成员变量过多,势必会占用比较大的资源,而且每一次保存都会消耗一定的内存,这点需要注意
- 使用场景:后悔药、数据库事务的管理、IE中的后退
- 为了节省内存,备忘录模式可以和原型模式配合使用