《大話設計模式》Java程式碼示例(十四)之備忘錄模式
阿新 • • 發佈:2018-12-20
備忘錄模式(Memonto):在不破壞封裝性的前提下,捕獲一個物件的內部狀態,並在該物件之外儲存這個狀態,這樣以後就可將該物件恢復到原先儲存的狀態。
package memento; /** * 備忘錄模式(Memento) * 遊戲角色 */ 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); 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(); } }
package memento; /** * 備忘錄模式(Memento) * 遊戲角色狀態儲存箱 */ 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; } }
package memento; /** * 備忘錄模式(Memento) * 遊戲角色狀態管理者 */ public class RoleStateCaretaker { private RoleStateMemento memento; public RoleStateMemento getMemento() { return memento; } public void setMemento(RoleStateMemento memento) { this.memento = memento; } }
package memento;
/**
* 備忘錄模式(Memento)
* 客戶端main方法
*/
public class Client {
public static void main(String[] args) {
// 打Boss前
GameRole lixiaoyao = new GameRole();
lixiaoyao.getInitState();
lixiaoyao.stateDisplay();
// 儲存進度
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.setMemento(lixiaoyao.saveState());
// 打Boss時,GameOver了
lixiaoyao.fight();
lixiaoyao.stateDisplay();
// 恢復之前狀態
lixiaoyao.recoveryState(stateAdmin.getMemento());
lixiaoyao.stateDisplay();
}
}