设计模式之备忘录模式
2010-11-19 13:44
411 查看
备忘录模式:当对象的状态需要回到前面某个状态时,可以通过备忘录模式,定义需要保存的细节的类,对需要保存的细节进行保存。这样,当需要保存的细节变化时,也不会影响到客户端
#region 备忘录模式 /// <summary> /// 备忘类,需要保存的数据集合 /// </summary> class GameRoleMemento { private int atk; //攻击力 private int def; //防御力 private int vit; //生命力 public int Vitality { set { vit = value; } get { return vit; } } public int Attack { set { atk = value; } get { return atk; } } public int Defense { set { def = value; } get { return def; } } public GameRoleMemento(int atk, int def, int vit) { this.atk = atk; this.def = def; this.vit = vit; } } /// <summary> /// 角色状态管理类,负责管理备忘类 /// </summary> class GameRoleCareTaker { private GameRoleMemento _gameRoleMemento; public GameRoleMemento Memento { set { _gameRoleMemento = value; } get { return _gameRoleMemento; } } } /// <summary> /// 游戏角色类 /// </summary> class GameRole { private string gameTitle; private string name; private int atk; //攻击力 private int def; //防御力 private int vit; //生命力 public string GameTitle { set { gameTitle = value; } get { return gameTitle; } } public string Name { set { name = value; } get { return name; } } public int Vitality { set { vit = value; } get { return vit; } } public int Attack { set { atk = value; } get { return atk; } } public int Defense { set { def = value; } get { return def; } } public GameRole(string gameTitle, string name) { this.gameTitle = gameTitle; this.name = name; } public GameRoleMemento SaveGameData() { return new GameRoleMemento(atk, def, vit); } public void RecoveryGameRole(GameRoleMemento gameRoleMemento) { this.vit = gameRoleMemento.Vitality; this.def = gameRoleMemento.Defense; this.atk = gameRoleMemento.Attack; } public void GetInitialData() { this.vit = 100; this.def = 100; this.atk = 100; } public void Fight() { this.vit = Convert.ToInt32(this.vit * 0.8); this.def = Convert.ToInt32(this.def * 0.5); this.atk = Convert.ToInt32(this.atk * 0.9); } public void DisplayData() { Console.WriteLine("{0}角色{1}当前状态值:", gameTitle, name); Console.WriteLine("生命值:{0}", this.vit); Console.WriteLine("攻击力:{0}", this.atk); Console.WriteLine("防御力:{0}", this.def); } } #endregion class Program { static void Main(string[] args) { #region 备忘录模式 Console.WriteLine("备忘录模式效果演示:"); GameRole 韩菱纱 = new GameRole("仙剑四", "韩菱纱"); 韩菱纱.GetInitialData(); 韩菱纱.DisplayData(); GameRoleCareTaker c = new GameRoleCareTaker(); c.Memento = 韩菱纱.SaveGameData(); 韩菱纱.Fight(); 韩菱纱.DisplayData(); 韩菱纱.RecoveryGameRole(c.Memento); 韩菱纱.DisplayData(); #endregion } }
相关文章推荐
- Android设计模式-备忘录模式
- c#设计模式之备忘录模式
- 设计模式——外观模式和备忘录模式
- 设计模式学习--备忘录模式
- Design Pattern Memo 备忘录设计模式
- Java设计模式-----Memento备忘录模式
- 设计模式之备忘录模式Memento
- c++ 23种设计模式之备忘录模式
- Android设计模式系列(5)--SDK源码之备忘录模式
- c++设计模式之备忘录模式
- GOF 23 设计模式之 备忘录模式(Memento)
- 设计模式(18)-备忘录模式
- C#设计模式(十八)备忘录模式
- 设计模式C++实现(12)——备忘录模式2
- [设计模式笔记]三. 行为型模式--20. Memento模式(备忘录)对象行为型模式(一)
- Java设计模式学习记录-备忘录模式
- 设计模式之备忘录模式
- 设计模式之Memento(备忘录)
- 【设计模式】备忘录模式
- 设计模式完整备忘录(转)