备忘录模式(Memento)
来源:互联网 发布:淘宝上买的锁芯 编辑:程序博客网 时间:2024/06/03 19:22
情节:如果再给我一次机会。。。
定义:在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
结构图:
public class GameRole {public int vit;public int atk;public int defense;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 getDefense() {return defense;}public void setDefense(int defense) {this.defense = defense;}public void StateDisplay(){System.out.println("VIT"+this.vit);System.out.println("ATK"+this.atk);System.out.println("DEFENSE"+this.defense);}public void GetInitState(){this.atk = 100;this.defense = 100;this.vit = 100;}public void Fight(){this.atk = 0;this.defense = 0;this.vit = 0;}//保存角色状态public Memento SaveState(){return new Memento(vit, atk, defense);}//恢复角色状态public void RecoveryState(Memento memento){this.atk = memento.atk;this.defense = memento.defense;this.vit = memento.vit;}}public class Memento {//体力,攻击力,防御力public int vit;public int atk;public int defense;public Memento(int vit, int atk, int defense) {super();this.vit = vit;this.atk = atk;this.defense = defense;}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 getDefense() {return defense;}public void setDefense(int defense) {this.defense = defense;}}public class Caretaker {private Memento memento;public Memento getMemento() {return memento;}public void setMemento(Memento memento) {this.memento = memento;}}public class Client {public static void main(String[] args) {//大战前GameRole xiaoRole = new GameRole();xiaoRole.GetInitState();xiaoRole.StateDisplay();//保存进度Caretaker stateAdmin = new Caretaker();stateAdmin.setMemento(xiaoRole.SaveState());//大战时xiaoRole.Fight();xiaoRole.StateDisplay();//恢复之前状态xiaoRole.RecoveryState(stateAdmin.getMemento());xiaoRole.StateDisplay();}}
把要保存的细节封装在Memento中,哪一天要更改保存的细节就不用影响客户端了
比较适用于功能比较复杂的,但需要维护或记录属性历史的类;需要保存的属性只是众多属性的一小部分时,Originator可以根据保存的Memento信息还原到前一状态。
0 0
- Memento模式 备忘录模式
- 备忘录模式(Memento Pattern)
- 备忘录模式(Memento Pattern)
- 备忘录(Memento)模式
- 备忘录模式(Memento Pattern)
- 备忘录(Memento)模式
- Memento 备忘录模式
- 15 Memento 备忘录模式
- 备忘录模式(Memento)
- Memento(备忘录模式)
- Memento备忘录模式
- 19.备忘录模式--Memento
- java Memento(备忘录模式)
- 备忘录模式 Memento Pattern
- 备忘录模式(Memento Pattern)
- Memento备忘录模式
- 备忘录模式(Memento)
- 备忘录模式(Memento Pattern)
- robotium不启动应用的错误解决方法
- 正则实现多词筛选
- Android WebView 缓存处理
- 又一城再获阿里巴巴“金牌淘拍档”
- PHP的一些案例研究(二)
- 备忘录模式(Memento)
- SCAMPIV1.3b的有趣变化----行动计划复评20问
- Linux设备模型分析之bus
- 关于performSelector延迟调用后无法走dealloc方法
- 远程访问Server2003的权限管理及设置
- 查看修改mysql编码方式
- 浅谈.NET非托管资源垃圾回收与程序资源优化(弱引用)
- maven标签大全
- 交叉编译链制作及调试