【Unity与23种设计模式】备忘录模式(Memento)
来源:互联网 发布:php商城系统 开源 编辑:程序博客网 时间:2024/05/27 20:54
GoF中定义:
“在不违反封装的原则下,获取一个对象的内部状态并保留在外部,让对象可以在日后恢复到原先保留时的状态。”
对于一些需要存储的数据,比如历史最高分
当与得分减分系统写入一个类时,违反了单一职责原则
最好是做一个SaveData的类单独存储或获取
而当使用一个单独的类时,又必须将数据public向外公开
这就将游戏置于危险的境地,甚至是方便了外挂横行
针对此矛盾局势
备忘录模式便解决了这一问题
备忘录模式可以描述为:
在不增加各个游戏系统类成员的“存取”方法的前提之下
存盘功能要能够获取各个游戏系统内部需要保存的信息
然后再游戏重新开始时,再将记录读取,并重新设置给各个游戏系统
备忘录模式的原理是:
游戏系统提供存取内部成员的方法,是让游戏系统处于“被动”状态
备忘录模式则是将游戏系统由“被动”改为“主动”提供
意思是让游戏系统自己决定要提供什么信息和记录存盘功能
也由游戏系统决定要从存盘功能中,读取什么样的数据及记录还原给内部成员
//需要存储的内容信息public class Originator { string m_State;//需要被保存的状态 public void SetInfo(string State) { m_State = State; } public void ShowInfo() { Debug.Log("Originator State:" + m_State); } public Memento CreateMemento() { Memento newMemento = new Memento(); newMemento.SetState(m_State); return newMemento; } public void SetMemento(Memento m) { m_State = m.GetState(); }}
//存放Originator对象的内部状态public class Memento { string m_State; public string GetState() { return m_State; } public void SetState(string State) { m_State = State; }}
//测试类public class TestMemento { void UnitTest() { Originator theOriginator = new Originator(); theOriginator.SetInfo("Step1"); theOriginator.ShowInfo(); Memento theMemento = theOriginator.CreateMemento(); theOriginator.SetInfo("Step2"); theOriginator.ShowInfo(); theOriginator.SetMemento(theMemento); theOriginator.ShowInfo(); }}
//Originator State:Info:Step1//Originator State:Info:Step2//Originator State:Info:Step1
文章整理自书籍《设计模式与游戏完美开发》 菜升达 著
阅读全文
0 0
- 【Unity与23种设计模式】备忘录模式(Memento)
- 23种设计模式之备忘录模式(Memento)
- 设计模式----Memento(备忘录)
- Memento(备忘录)设计模式
- 设计模式23:Memento Pattern (备忘录模式)
- 23设计模式之备忘录模式(Memento)
- 23设计模式之备忘录模式(Memento)
- java设计模式-备忘录模式(Memento)
- 设计模式之备忘录模式(Memento)
- 设计模式--备忘录模式(Memento)
- Java设计模式----备忘录模式(Memento)
- 设计模式之:备忘录模式(Memento)
- 设计模式-备忘录模式(Memento)
- 设计模式:备忘录模式(Memento)
- 设计模式:备忘录模式(Memento)
- 设计模式(19)-备忘录模式(Memento)
- 设计模式之备忘录模式(Memento)
- [设计模式]备忘录模式(Memento)
- ①设计模式之策略模式
- Network UVA
- php中的spl(供自己使用)
- 聚类(R)
- 一个例子中this的指向分析思路
- 【Unity与23种设计模式】备忘录模式(Memento)
- 批量显示JOB Log
- java新特性-枚举
- 搭建ARM i287编译
- Androi--内容提供器
- 测试入门之定义和目的
- SpannableString的点击事件以及颜色设置ClickableSpan
- 给你一个承诺
- Maven项目中spring异常之CannotLoadBeanClassException