题目:
使用备忘录模式实现游戏中存档的功能。存档的属性包括血量、攻击力、防御力三种。
类图:
代码:
package Memento;
class RoleStateMemento
{
private int vit;
private int atk;
private int def;
RoleStateMemento(int vit, int atk, int def){
this.vit = vit;
this.atk = atk;
this.def = def;
}
public void setVit(int vit){ this.vit = vit; }
public int getVit(){ return this.vit; }
public void setAtk(int atk){ this.atk = atk; }
public int getAtk(){ return this.atk; }
public void setDef(int def){ this.def = def; }
public int getDef(){ return this.def; }
};
class GameRole
{
private int vit;
private int atk;
private int def;
public void initState()
{
this.vit = 1000;
this.atk = 100;
this.def = 100;
}
public void setVit(int vit){ this.vit = vit; }
public int getVit(){ return this.vit; }
public void setAtk(int atk){ this.atk = atk; }
public int getAtk(){ return this.atk; }
public void setDef(int def){ this.def = def; }
public int getDef(){ return this.def; }
public void stateDisplay()
{
System.out.println("角色当前状态:");
System.out.println("生命值:" + this.vit);
System.out.println("攻击力:" + this.atk);
System.out.println("防御力:" + this.def);
}
public RoleStateMemento saveState()
{
return new RoleStateMemento(this.vit, this.atk, this.def);
}
public void recoveryState(RoleStateMemento memento)
{
this.vit = memento.getVit();
this.atk = memento.getAtk();
this.def = memento.getDef();
}
};
class RoleStateCarataker
{
private RoleStateMemento memento;
public void setRoleStateMemento(RoleStateMemento memento){ this.memento = memento; }
public RoleStateMemento getRoleStateMemento(){ return this.memento; }
};
public class GameSave {
public static void main(String[] args){
System.out.println("打BOSS前存档" );
GameRole gr = new GameRole();
gr.initState();
gr.stateDisplay();
RoleStateCarataker stateAdmin = new RoleStateCarataker();
stateAdmin.setRoleStateMemento(gr.saveState());
gr.setVit(0);
System.out.println("打BOSS前存档" );
gr.stateDisplay();
gr.recoveryState(stateAdmin.getRoleStateMemento());
System.out.println("读取档案重新开始" );
gr.stateDisplay();
}
}
结果: