设计模式(十四)——备忘录模式
来源:互联网 发布:合金装备 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
阅读全文
1 0
- 设计模式—备忘录模式(十四)
- 设计模式(十四)——备忘录模式
- 设计模式(十四)备忘录模式
- 十四、备忘录模式——设计模式学习笔记
- (十四)备忘录模式
- 设计模式实现(十四)--- 备忘录模式(Memento)
- 设计模式之十四:备忘录模式(Memento)
- 第二十四篇 设计模式--备忘录模式
- 设计模式学习(十四):备忘录模式
- 设计模式C++实现十四:备忘录模式
- Java设计模式《十四》备忘录模式
- 设计模式—备忘录模式
- 十四、备忘录模式
- 每日设计模式——备忘录模式
- 设计模式——备忘录模式(Memento)
- 设计模式——备忘录模式
- java设计模式——备忘录模式
- JAVA设计模式——备忘录模式
- JAVA调用ImageCapOnWeb控件实现拍照功能
- angular API
- 最小树形图
- 如何一次终止同一名字的多个进程
- 分布式缓存Redis之配置文件redis.conf详解
- 设计模式(十四)——备忘录模式
- A07_文本文件的读写
- android Logcat打印格式说明
- vmware workstation 14 黑屏 解决方法
- unity创建小地图
- mysql日常 bug发现
- 171207之java中的JSON序列化问题
- Masonry学习之链式属性
- javascript JSON.parse() JSON.stringify() 和jquery.parseJOSN() 使用与区别