设计模式_14:备忘录模式
来源:互联网 发布:java四大特性简单概述 编辑:程序博客网 时间:2024/05/21 16:56
我们玩单机RPG游戏的时候,通常会在打Boss前存个档,方便输掉的时候直接读取进度,这就是典型的备忘录模式:
public class Main { public static void main(String[] args) { GameRole hero = new GameRole(); RoleStateCaretaker roleStateCaretaker = new RoleStateCaretaker(); System.out.println(hero); System.out.println("进度保存中..."); roleStateCaretaker.setRoleStateMemento(hero.saveState()); System.out.println("进度保存完成!去打Boss咯~"); hero.fightBoss(); System.out.print("打Boss后,"); System.out.println(hero); System.out.println("读取进度中..."); hero.loadState(roleStateCaretaker.getRoleStateMemento()); System.out.println("读取进度完成!"); System.out.println(hero); }}//游戏角色(Originator:存档发起人)class GameRole { private int str; //力 private int vit; //体 private int def; //防 public GameRole() { this.str = 100; this.vit = 100; this.def = 100; } public int getStr() { return str; } public void setStr(int str) { this.str = str; } public int getVit() { return vit; } public void setVit(int vit) { this.vit = vit; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } //保存状态 public RoleStateMemento saveState(){ return new RoleStateMemento(this.str, this.vit, this.def); } //读取状态 public void loadState(RoleStateMemento memento){ this.str = memento.getStr(); this.vit = memento.getVit(); this.def = memento.getDef(); } //打后 public void fightBoss(){ this.str = 0; this.vit = 0; this.def = 0; } @Override public String toString() { return "当前角色状态:{" + "str=" + str + ", vit=" + vit + ", def=" + def + '}'; }}//角色状态存档(Memento:备忘录)class RoleStateMemento { private int str; //力 private int vit; //体 private int def; //防 public RoleStateMemento(int str, int vit, int def) { this.str = str; this.vit = vit; this.def = def; } public int getStr() { return str; } public int getVit() { return vit; } public int getDef() { return def; }}//RoleStateCaretaker(Caretaker:备忘录管理者)class RoleStateCaretaker { private RoleStateMemento memento; public RoleStateMemento getRoleStateMemento() { return memento; } public void setRoleStateMemento(RoleStateMemento memento) { this.memento = memento; }}运行结果:
当前角色状态:{str=100, vit=100, def=100}进度保存中...进度保存完成!去打Boss咯~打Boss后:当前角色状态:{str=0, vit=0, def=0}读取进度中...读取进度完成!当前角色状态:{str=100, vit=100, def=100}
阅读全文
1 0
- 设计模式_14:备忘录模式
- 建造者模式(设计模式_14)
- 设计模式-----备忘录模式
- 设计模式 备忘录模式
- 【设计模式】备忘录模式
- 设计模式 - 备忘录模式
- 设计模式:备忘录模式
- 设计模式 - 备忘录模式
- 设计模式 - 备忘录模式
- 设计模式 - 备忘录模式
- 设计模式:备忘录模式
- 【设计模式】备忘录模式
- 设计模式-备忘录模式
- 设计模式--备忘录模式
- 设计模式--备忘录模式
- 设计模式--备忘录模式
- 设计模式-备忘录模式
- 设计模式-备忘录模式
- 410c安卓分区
- windows环境下编译spark源码和搭建源码调试环境
- go.js的一些功能
- 介绍vue-cli
- -webkit-tap-highlight-color 属性 及 active伪类在手机端无效
- 设计模式_14:备忘录模式
- scanf函数库解决问题
- linux打包和解压缩到指定目录
- vnc配置和display操作(杂)
- vue.js的devtools安装
- 错误更新了全表数据之后,教你如何恢复数据
- 真正搭建部署greenplum
- git教程
- 安装Mysql图文教程