备忘录模式——对象行为型模式
来源:互联网 发布:淘宝外卖点麻辣烫 编辑:程序博客网 时间:2024/04/30 18:03
一、意图
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
二、适用性
以下情况使用备忘录模式:
- 必须保存一个对象在某一时刻的(部分)状态,这样以后需要时它才能恢复到先前的状态。
- 如果一个用接口来让其它对象直接取得这些状态,将会暴露对象的实现细节并破坏对象的封装性。
三、结构
四、代码
public class CallOfDuty { private int mCheckpoint = 1; private int mLifeValue = 100; private String mWeapon = "沙漠之鹰"; public void play() { System.out.println("玩游戏: " + String.format("第%d关", mCheckpoint) + "奋战杀敌中"); mLifeValue -= 10; System.out.println("进度升级啦"); mCheckpoint++; System.out.println("到达 " + String.format("第%d关", mCheckpoint)); } public void quit() { System.out.println("-----------------"); System.out.println("退出前游戏属性: " + this.toString()); System.out.println("退出游戏"); System.out.println("-----------------"); } public Memento createMemento() { Memento memento = new Memento(); memento.mCheckPoint = this.mCheckpoint; memento.mLifeValue = this.mLifeValue; memento.mWeapon = this.mWeapon; return memento; } public void restore(Memento memento){ this.mCheckpoint =memento.mCheckPoint; this.mLifeValue = memento.mLifeValue; this.mWeapon = memento.mWeapon; System.out.println("恢复后的游戏属性: "+this.toString()); } @Override public String toString() { return "CallOfDuty{" + "mCheckpoint=" + mCheckpoint + ", mLifeValue=" + mLifeValue + ", mWeapon='" + mWeapon + '\'' + '}'; }}
public class Memento { public int mCheckPoint; public int mLifeValue; public String mWeapon; @Override public String toString() { return "Memento{" + "mCheckPoint=" + mCheckPoint + ", mLifeValue=" + mLifeValue + ", mWeapon='" + mWeapon + '\'' + '}'; }}
public class Caretaker { Memento memento; public void archive(Memento memento){ this.memento = memento; } public Memento getMemento(){ return memento; }}
public class Client { public static void main(String[] args){ // 构建游戏对象 CallOfDuty game = new CallOfDuty(); game.play(); Caretaker caretaker = new Caretaker(); caretaker.archive(game.createMemento()); game.quit(); CallOfDuty newGame = new CallOfDuty(); newGame.restore(caretaker.memento); }}
1 0
- 备忘录模式——对象行为型模式
- 备忘录——对象行为模式
- Memento 备忘录模式 ----对象行为型模式
- 备忘录模式-对象行为模式
- 备忘录模式Memento(对象行为型)
- Memento(备忘录)——对象行为模式
- 备忘录模式(行为型)
- 行为型模式之五——备忘录模式
- JAVA设计模式(19) —<行为型>备忘录模式(Memento)
- 【设计模式】—-(18)备忘录模式(行为型)
- 行为型模式--备忘录模式
- 行为型模式-备忘录模式
- [设计模式笔记]三. 行为型模式--20. Memento模式(备忘录)对象行为型模式(一)
- 设计模式 - 行为型模式 - 备忘录模式
- 设计模式->行为型模式->备忘录模式
- 行为模式--备忘录模式
- 行为模式-备忘录模式
- 备忘录模式 - 行为模式
- Extjs中treeStore自动提交leaf字段
- 选择时间日历控件DatePickerDialog实现(从外包项目中挖出来整理的)
- A*寻路算法学习及实现
- 分析函数:first_value,last_value用法
- 为JAXB和response设置编码,解决wechat4j中文乱码
- 备忘录模式——对象行为型模式
- bitmap的oom问题
- Redis 配置文件 详解
- C语言中宏定义(#define)时do{...}while(0)的价值
- js函数的闭包
- js事件的分类和介绍
- Composer更新缓慢的解决方案
- 在布局中使用include引入其他layout时引发click事件不触发的问题
- 如何将git远程分支更新到本地