備忘錄模式
備忘錄模式是一種軟件設計模式:在不破壞封閉的前提下,捕獲一個對象的內部狀態,並在該對象之外保存這個狀態。這樣以后就可將該對象恢復到原先保存的狀態。一聽到備忘錄這個字的時候想起了小小時打的游戲,每次遇到大boss的時候都會保存一下進度,打過了就不需要恢復記錄,打不過肯定就復原到剛剛保存的記錄咯,重新打一遍BOSS,打死為止。哈哈,這就是備忘錄模式,雖然很多模式都只是學到基礎,但是發現越來越接近生活了。
涉及角色:
Originator(發起人):負責創建一個備忘錄Memento,用以記錄當前時刻自身的內部狀態,並可使用備忘錄恢復內部狀態。Originator可以根據需要決定Memento存儲自己的哪些內部狀態。
Memento(備忘錄):負責存儲Originator對象的內部狀態,並可以防止Originator以外的其他對象訪問備忘錄。備忘錄有兩個接口:Caretaker只能看到備忘錄的窄接口,他只能將備忘錄傳遞給其他對象。Originator卻可看到備忘錄的寬接口,允許它訪問返回到先前狀態所需要的所有數據。
Caretaker(管理者):負責備忘錄Memento,不能對Memento的內容進行訪問或者操作。
備忘錄模式UML圖
備忘錄模式代碼
package com.roc.meomory; /** * 游戲角色 * @author liaowp * */ public class GameRole { private int vit; private int atk; public void init(){ vit=100; atk=100; } public void show(){ System.out.println("體力:"+vit); System.out.println("攻擊力:"+atk); } public void fightBoss(){ this.vit=0; this.atk=0; } public RoleStateMemento saveMemento(){ return (new RoleStateMemento(vit, atk)); } public void recove(RoleStateMemento roleStateMemento){ this.vit=roleStateMemento.getVit(); this.atk=roleStateMemento.getAtk(); } }
package com.roc.meomory; /** * 游戲角色管理類 * @author liaowp * */ public class RoleStateMange { private RoleStateMemento memento; public RoleStateMemento getMemento() { return memento; } public void setMemento(RoleStateMemento memento) { this.memento = memento; } }
package com.roc.meomory; /** * 存儲類 * @author liaowp * */ public class RoleStateMemento { private int vit; private int atk; public RoleStateMemento(int vit, int atk){ this.vit=vit; this.atk=atk; } 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; } }
package com.roc.meomory; /** * 備忘錄模式 * @author liaowp * */ public class Client { public static void main(String[] args) { GameRole liaowp=new GameRole(); liaowp.init(); liaowp.show(); RoleStateMange adminMange=new RoleStateMange(); adminMange.setMemento(liaowp.saveMemento());//保存 liaowp.fightBoss(); liaowp.show(); liaowp.recove(adminMange.getMemento()); liaowp.show(); } }
備忘錄模式適用場景
適合功能比較復雜的,但需要維護或記錄屬性歷史的功能。