备忘录(Memento),在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
举例:
比如玩单机游戏,一般打大boss前,或者需要下线了,都会把当前的状态保存一份,避免打boss死亡或者角色数据丢失,这个就可以用备忘录模式来实现。
1.游戏备忘录类,记录需要存档的数据信息
public class RoleStateMemento {
// 生命力
private int vit;
// 攻击力
private int atk;
// 防御力
private int def;
public RoleStateMemento(int vit, int atk, int def) {
this.vit = vit;
this.atk = atk;
this.def = def;
}
public int getVit() {
return vit;
}
public int getAtk() {
return atk;
}
public int getDef() {
return def;
}
}
2.游戏角色类
import java.util.Random;
public class Player {
// 生命力
private int vit = 100;
// 攻击力
private int atk = 100;
// 防御力
private int def = 100;
// 保存角色状态
public RoleStateMemento saveState(){
return new RoleStateMemento(vit, atk, def);
}
// 恢复角色
public void RecoveryState(RoleStateMemento backup){
this.vit = backup.getVit();
this.atk = backup.getAtk();
this.def = backup.getDef();
}
// 战斗
public void fight(){
Random random = new Random();
this.vit = random.nextInt(99);
this.atk = random.nextInt(99);
this.def = random.nextInt(99);
}
// 展示属性
public void show(){
System.out.println("生命力:" + vit + " 攻击力:" + atk + " 防御力:" + def);
}
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getAtk() {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
}
3.游戏角色状态管理者
public class RoleAdmin {
private RoleStateMemento roleStateMemento;
public RoleStateMemento getRoleStateMemento() {
return roleStateMemento;
}
public void setRoleStateMemento(RoleStateMemento roleStateMemento) {
this.roleStateMemento = roleStateMemento;
}
}
4.主程序
public class Test {
public static void main(String[] args) {
Player player = new Player();
player.show();
// 保存状态
RoleAdmin roleAdmin = new RoleAdmin();
roleAdmin.setRoleStateMemento(player.saveState());
// 开始战斗
player.fight();
player.show();
// 状态不好了,恢复到战斗前的状态
player.RecoveryState(roleAdmin.getRoleStateMemento());
player.show();
}
}
运行结果如下:
总结:
备忘录模式比较适用于功能比较复杂的,但需要维护或者记录历史属性的类,或者需要保存的属性只是众多属性中的一小部分时,Originator可以根据保存的Memento信息还原到前一状态。如果状态数据过大的话,备忘录模式会非常消耗内存,在做java企业级应用时,一般都选择定时将数据持久化到数据库中做备份。