备忘录模式
备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象。
备忘录模式优缺点
优点
给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态。
缺点
消耗资源。如果类的成员变量过多,势必会占用比较大的资源,而且每一次保存都会消耗一定的内存。
应用场景
-
需要保存/恢复数据的相关状态场景。
-
提供一个可回滚的操作。
备忘录模式结构
-
发起人角色:记录当前时刻的内部状态,负责创建和恢复备忘录数据。
-
备忘录角色:负责存储发起人对象的内部状态,在进行恢复时提供给发起人需要的状态。
-
管理者角色:负责保存备忘录对象。
实现流程
发起人角色
public class GameRole {
private int vit;//生命力
private int atk;//攻击力
private int def;//防御力
//初始化内部状态
public void initState(){
this.atk = 100;
this.vit = 100;
this.def = 100;
}
//战斗
public void fight(){
this.atk = 0;
this.vit = 0;
this.def = 0;
}
//保存角色状态功能
public RoleStateMementto save(){
return new RoleStateMementto(vit,atk,def);
}
//恢复角色状态
public void recoverState(RoleStateMementto roleStateMementto){
// 将备忘录中存储的状态赋值给当前对象的成员
this.vit = roleStateMementto.getVit();
this.atk = roleStateMementto.getAtk();
this.def = roleStateMementto.getDef();
}
//展示状态功能
public void display(){
System.out.println("角色的生命力是"+vit);
System.out.println("角色的攻击力是"+atk);
System.out.println("角色的防御力是"+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;
}
}
备忘录角色
public class RoleStateMementto {
private int vit; //生命力
private int atk; //攻击力
private int def; //防御力
public RoleStateMementto(int vit, int atk, int def) {
this.vit = vit;
this.atk = atk;
this.def = 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;
}
}
备忘录对象管理对象
public class RoleStateCaretaker {
private RoleStateMementto roleStateMementto;
public RoleStateMementto getRoleStateMementto(){
return roleStateMementto;
}
public void setRoleStateMementto(RoleStateMementto roleStateMementto){
this.roleStateMementto = roleStateMementto;
}
}