标签:image snapshot alt 复杂 img 备忘录 class rgs 行为模式
备忘录模式(Memento Pattern)
备忘录模式(Memento Pattern)又叫做快照模式(Snapshot Pattern)或Token模式,是GoF的23种设计模式之一,属于行为模式。
定义:在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
public class Memento { private int bloodflow;//生命值 private int magicpoint;//魔法值 public int getBloodflow() { return bloodflow; } public void setBloodflow(int bloodflow) { this.bloodflow = bloodflow; } public int getMagicpoint() { return magicpoint; } public void setMagicpoint(int magicpoint) { this.magicpoint = magicpoint; } public Memento(int bloodflow, int magicpoint) { this.bloodflow = bloodflow; this.magicpoint = magicpoint; } }
3.创建Caretaker类管理Memento
public class Caretaker { private Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
4.编写Role角色类并写出获取角色当前状态,存档时的状态,以及恢复存档时的状态
public class Role { //血量 private int bloodflow; //魔法值 private int magicpoint; public int getBloodflow() { return bloodflow; } public void setBloodflow(int bloodflow) { this.bloodflow = bloodflow; } public int getMagicpoint() { return magicpoint; } public void setMagicpoint(int magicpoint) { this.magicpoint = magicpoint; } public Role(int bloodflow, int magicpoint) { this.bloodflow = bloodflow; this.magicpoint = magicpoint; } /** * 角色当前状态 */ public void dispaly() { System.out.println("用户当前状态:"); System.out.println("血量:"+getBloodflow()+"魔法值:"+getMagicpoint()); } /** *保持存档,当前状态 */ public Memento saveMemento() { return new Memento(getBloodflow(),getMagicpoint()); } /** * 恢复存档 */ public void restoreMemento(Memento memento) { this.bloodflow=memento.getBloodflow(); this.magicpoint=memento.getMagicpoint(); } }
5.测试类代码
public class Client { public static void main(String[] args) { //打Boss之前,血和蓝全部满值 Role role=new Role(100, 100); System.out.println("=====大战Boss前======"); role.dispaly(); //保持进度 Caretaker caretaker=new Caretaker(); Memento saveMemento = role.saveMemento(); //大战Boss之后,快挂了 role.setBloodflow(20); role.setMagicpoint(10); System.out.println("=====大战Boss后======"); role.dispaly(); //恢复存档 role.restoreMemento(saveMemento); System.out.println("=====恢复======"); role.dispaly(); } }
实现效果:
标签:image snapshot alt 复杂 img 备忘录 class rgs 行为模式
原文地址:http://www.cnblogs.com/Smile-123/p/6053485.html