简单梳理备忘录模式
备忘录模式实现
我们在打游戏的时候,经常会遇到大Boss,打不过的时候,想恢复到打Boss之前的状态。
这种恢复到之前某个时间点的状态可以用备忘录模式来实现。
首先我们定义基本类,游戏角色类。
public class GameRole {
//生命力
private int vit;
//攻击力
private int atk;
//防御力
private int 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 void StateDisplay(){
System.out.println("角色当前状态:");
System.out.println("体力:"+this.vit);
System.out.println("攻击力:"+this.atk);
System.out.println("防御力:"+this.def);
}
//初始状态
public void GetInitState(){
this.vit=100;
this.atk=100;
this.def=100;
}
//战斗后
public void Fight(){
this.vit=0;
this.atk=0;
this.def=0;
}
//保存角色状态
public RoleStateMemento SaveState(){
return new RoleStateMemento(vit, atk, def);
}
//恢复角色状态
public void RecoveryState(RoleStateMemento roleStateMemento){
this.vit = roleStateMemento.getVit();
this.atk = roleStateMemento.getAtk();
this.def = roleStateMemento.getDef();
}
}
定义存储之前状态的类
//状态存储类
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 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 RoleStateMemento roleStateMemento;
public RoleStateMemento getRoleStateMemento() {
return roleStateMemento;
}
public void setRoleStateMemento(RoleStateMemento roleStateMemento) {
this.roleStateMemento = roleStateMemento;
}
}
这样我们前期的定义就算做完了,
然后我们看具体应用中的使用。
定义业务方法
看在具体业务逻辑中如何使用
public class MementoTest {
public static void main(String[] args) {
//备忘录模式
func1();
}
public static void func1(){
//大战前
GameRole lixiaoyao = new GameRole();
lixiaoyao.GetInitState();
lixiaoyao.StateDisplay();
//保存进度
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.setRoleStateMemento(lixiaoyao.SaveState());
//大战Boss,损耗严重
lixiaoyao.Fight();
lixiaoyao.StateDisplay();
//恢复之前的状态
lixiaoyao.RecoveryState(stateAdmin.getRoleStateMemento());
lixiaoyao.StateDisplay();
}
}
执行结果
角色当前状态:
体力:100
攻击力:100
防御力:100
角色当前状态:
体力:0
攻击力:0
防御力:0
角色当前状态:
体力:100
攻击力:100
防御力:100
结果分析
备忘录模式,在不破坏封装的前提下,捕获一个对象的内部状态,
并在该对象之外,保存这个状态。
这样就可以将该对象恢复到之前的某个状态。
备忘录模式适用于功能比较复杂的,但需要记录和维护属性历史的类。
或者需要保存的属性是众多属性中的一小部分时,可以根据保存的信息还原到前一状态。
联系作者
微信公众号
xiaomingxiaola
(BossLiu)
QQ群
58726094
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 384276224@qq.com