以玩游戏为例,大战boss前保存角色状态,大战过boss之后恢复角色大战boss之前的状态。
package com.wzs.design;
/**
* 大话设计模式--page186 备忘录模式
*
* @author Administrator
*
*/
public class MemoMode {
public static void main(String[] args) {
// 大战boss前
GameRole lixiaoyao = new GameRole();
lixiaoyao.getInitState();
lixiaoyao.stateDisplay();
// 保存进度
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.memento = lixiaoyao.saveState();
// 大战boss,损耗严重
lixiaoyao.fight();
lixiaoyao.stateDisplay();
// 回复之前状态
lixiaoyao.recoveryState(stateAdmin.memento);
lixiaoyao.stateDisplay();
}
}
/*
* 游戏角色
*/
class GameRole {
private int vit; // 生命力
private int atk; // 攻击力
private int def; // 防御力
// 状态显示
public void stateDisplay() {
System.out.println("角色当前状态:");
System.out.println("生命力:" + this.vit);
System.out.println("攻击力:" + this.atk);
System.out.println("防御力:" + this.def);
System.out.println();
}
// 获得初始状态
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 memento) {
this.vit = memento.getVit();
this.atk = memento.getAtk();
this.def = memento.getDef();
}
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;
}
}
/*
* 角色状态存储箱
*/
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;
}
}
/*
* 角色状态管理者
*/
class RoleStateCaretaker {
public RoleStateMemento memento;
public RoleStateMemento getMemento() {
return memento;
}
public void setMemento(RoleStateMemento memento) {
this.memento = memento;
}
}