备忘录模式
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态
为了节约内存,备忘录模式可以和原型模式配合使用(原型模式可以克隆对象,性能更高)
1、需要保存/恢复数据的相关状态场景
2、数据库的事务管理
游戏角色有攻击力和防御力,在大战 Boss 前保存自身的状态(攻击力和防御力),当大战 Boss 后攻击力和防御力
下降,从备忘录对象恢复到大战前的状态~
步骤如下:
1) 定义Memento类,定义一些基本属性
2) 定义GameRole类,根据当前状态获取Memento
3) 定义Caretaker类,此类为守护者对象,备份数据
4) 客户端调用
Memento类
/**
* @author 漆剑
* @date 2021-03-27
* @description
*/
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;
}
}
GameRole类
/**
* @author 漆剑
* @date 2021-03-27
* @description
*/
public class GameRole {
private int vit;
private int def;
//创建Memento 即根据当前状态得到Memrnto
public Memento createMemento(){
return new Memento(vit, def);
}
//从备忘录对象,恢复GameRole的状态
public void recoverGameRoleFromMemento(Memento memento){
vit = memento.getVit();
def = memento.getDef();
}
//显示当前游戏角色的状态
public void display(){
System.out.println("攻击力:"+vit +",防御力:"+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;
}
}
Caretaker类
/**
* @author 漆剑
* @date 2021-03-27
* @description
*/
//守护者对象:保存游戏角色的状态
public class Caretaker {
//如果只保存一次状态
private Memento memento;
//对FameRole保存多次状态
// private ArrayList<Memento> mementos;
//对多个游戏角色保存多个状态
// private HashMap<String,ArrayList<Memento>> rolesmementos;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
客户端调用
/**
* @author 漆剑
* @date 2021-03-27
* @description
*/
public class Client {
public static void main(String[] args) {
//创建游戏角色
GameRole gameRole = new GameRole();
gameRole.setVit(100);
gameRole.setDef(100);
System.out.println("大战前的状态");
gameRole.display();
//吧当前状态保存到caretaker
Caretaker caretaker = new Caretaker();
caretaker.setMemento(gameRole.createMemento());
System.out.println("和boss大战");
gameRole.setDef(30);
gameRole.setVit(30);
gameRole.display();
System.out.println("大战后使用备忘录对象恢复到大战前");
gameRole.recoverGameRoleFromMemento(caretaker.getMemento());
System.out.println("恢复后。。。。");
gameRole.display();
}
}
- 给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态
- 实现了信息的封装,使得用户不需要关心状态的保存细节
- 如果类的成员变量过多,势必会占用比较大的资源,而且每一次保存都会消耗一定的内存, 这个需要注意
由于水平有限,本博客难免有不足,恳请各位大佬不吝赐教!