备忘录(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
把要保存的细节给封装在了Memento 中了,哪一天要更改保存的细节也不用影响客户端了。
Memento模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中一小部分时,可以根据保存的Memento信息还原到前一状态。
使用命令模式,需要实现命令的撤销功能,那么命令模式可以使用备忘录模式来存储可撤销操作的状态。
OriginatorGameRole类
package memento; /** * 游戏角色类 * 负责创建备忘录 * 可使用备忘录恢复内部状态 * @author 煞笔 * */ public class OriginatorGameRole { private int vitality;//生命力,体力 private int attach;//攻击力 private int defense;//防御力 /** * 获取初始状态 */ public void getInitState(){ this.vitality = 100; this.attach = 100; this.defense = 100; } public Memento createMemento(){ return new Memento(attach,vitality); } public void recoveryMemento(Memento m){ attach = m.getAttach(); vitality = m.getVitality(); } public void Fight(){ this.vitality = 0; this.attach = 0; this.defense = 0; } public int getVitality() { return vitality; } public void setVitality(int vitality) { this.vitality = vitality; } public int getAttach() { return attach; } public void setAttach(int attach) { this.attach = attach; } public int getDefense() { return defense; } public void setDefense(int defense) { this.defense = defense; } public void show(){ System.out.println("游戏角色当前状态:"); System.out.println("体力:"+vitality); System.out.println("攻击力:"+attach); System.out.println("防御力:"+defense); } }
Memento类
package memento; /** * 备忘录角色类 * @author 煞笔 * */ public class Memento { private int vitality;//生命力 private int attach;//攻击力 public Memento(int vitality, int attach) { super(); this.vitality = vitality; this.attach = attach; } public int getVitality() { return vitality; } public void setVitality(int vitality) { this.vitality = vitality; } public int getAttach() { return attach; } public void setAttach(int attach) { this.attach = attach; } }
MementoManager类
package memento; /** * 负责人角色类,负责人角色负责保存备忘录对象,但是从不修改(甚至不查看)备忘录对象的内容 * @author 煞笔 * */ public class MementoManager { private Memento memento ; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
Busiess类
package memento; public class Busiess { public static void main(String[] args) { OriginatorGameRole quanyecha = new OriginatorGameRole(); quanyecha.getInitState(); quanyecha.show(); MementoManager mementoManager = new MementoManager(); mementoManager.setMemento(quanyecha.createMemento()); quanyecha.Fight(); quanyecha.show(); quanyecha.recoveryMemento(mementoManager.getMemento()); quanyecha.show(); } }