设计模式(十四)——备忘录模式

来源:互联网 发布:合金装备 mac 汉化 编辑:程序博客网 时间:2024/06/10 23:58

备忘录模式(Memento)

备忘录模式,在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

代码

1.代码如下:

游戏角色类

using System;namespace Memento{//游戏角色类public class GameRole{//生命力public int vitality;//攻击力public int attack;//防御力public int defense;//状态显示public void StateDisplay(){Console.WriteLine ("角色当前状态:");Console.WriteLine ("体力:{0}", this.vitality);Console.WriteLine ("攻击力:{0}", this.attack);Console.WriteLine ("防御力:{0}", this.defense);Console.WriteLine ("");}//获取初识状态public void GetInitState(){this.vitality = 100;this.attack = 100;this.defense = 100;}//战斗public void Fight(){this.vitality = 0;this.attack = 0;this.defense = 0;}//保存角色状态public RoleStateMemento SaveState(){return (new RoleStateMemento (vitality, attack, defense));}//恢复角色状态public void RecoveryState(RoleStateMemento memento){this.vitality = memento.vitality;this.attack = memento.attack;this.defense = memento.defense;}}}

角色状态存储类

using System;namespace Memento{//角色状态存储箱public class RoleStateMemento{//生命力public int vitality;//攻击力public int attack;//防御力public int defense;//状态显示public RoleStateMemento(int vitality,int attack,int defense){this.vitality=vitality;this.attack=attack;this.defense=defense;}}}

角色状态管理者

using System;namespace Memento{//角色状态管理者public class RoleStateCaretaker{private RoleStateMemento memento;public RoleStateMemento Memento{get{ return memento; }set{memento = value;}}}}
2.客户端代码如下:

客户端

using System;namespace Memento{class MainClass{public static void Main (string[] args){//大战Boss前GameRole gameRole=new GameRole();gameRole.GetInitState ();gameRole.StateDisplay ();//保存进度RoleStateCaretaker stateAdmin=new RoleStateCaretaker();stateAdmin.Memento = gameRole.SaveState ();//大战Boss时,损耗严重gameRole.Fight();gameRole.StateDisplay ();//恢复之前状态gameRole.RecoveryState(stateAdmin.Memento);gameRole.StateDisplay ();}}}
3.运行结果

UML图

源码下载地址:https://gitee.com/ZhaoYongshuang/DesignPattern.git
原创粉丝点击