备忘录模式

来源:互联网 发布:thumbdata怎么删除知乎 编辑:程序博客网 时间:2024/05/17 09:17

备忘录模式

备忘录模式(Memento)
  在以前的单机游戏中经常会有存储游戏进度,或者在看视频时中间端看下次再次打开会看见你原来的进度。这种保存之前软件进度的方式可以采用备忘录模式。看到这个就想起暴力摩托的破解版,里面有着所有的摩托供你玩,一开始你就是通关的,其实这个就是别人把已经通关的游戏状态持久化保存,你拿到后读取进度,相当于自己也通关了,可以尽情享受通关后的各种福利。比较常见的还有一个对操作系统制作Ghost镜像。
备忘录模式可以在不破坏封装性前提的条件下,捕获一个对象的状态,并在该对象之外保存该状态。这样就可以在需要的时候将这个对象恢复到原先的状态。
在一个备忘录模式中应该含有三种角色,发起者(Originator,即需要保存和在适当时候恢复的对象)、备忘录(Memento,保存originator状态的类)、管理者(CareTaker,负责保存备忘录,不能对备忘录进行操作或者检查等其他操作,只能保存或者传送备忘录对象)。
下面是一个游戏的角色状态保存,
1、创建发起者及游戏角色
public class GameRole {private int vit;private int atk;private int def;public RoleMemento createMemento() {return new RoleMemento(vit, atk, def);}public void restoreMemento(RoleMemento memento) {this.vit = memento.getVit();this.def = memento.getDef();this.atk = memento.getAtk();}public void initState() {this.vit = 100;this.atk = 0;this.def = 100;}public void fight() {this.vit = 0;this.atk = 100;this.def = 0;}public void showState() {System.out.println("Vitality:"+this.vit);System.out.println("Attack:"+this.atk);System.out.println("Defence:"+this.def);}}
这个类中含有创建备忘录并将其交给备忘录,和恢复备忘录的方法。
2、创建备忘录类
public class RoleMemento {private int vit;private int atk;private int def;public RoleMemento(int vit, int atk, int def) {super();this.vit = vit;this.atk = atk;this.def = def;}public int getVit() {return vit;}public int getAtk() {return atk;}public int getDef() {return def;}}

需要保存的状态值。

3、创建备忘录者管理者类
public class MementoManager {private RoleMemento memento;public RoleMemento getMemento() {return memento;}public void setMemento(RoleMemento memento) {this.memento = memento;}}

保存和对外提供备忘录

接着就是对于在运行中的使用了

public static void main(String[] args) {MementoManager manager = new MementoManager();GameRole role = new GameRole();role.initState();System.out.println("开始游戏前");role.showState();manager.setMemento(role.createMemento());//战斗前保存状态role.fight();System.out.println("战斗结束后");role.showState();role.restoreMemento(manager.getMemento());//战斗结束恢复状态System.out.println("恢复战斗前状态");role.showState();}
运行结果

开始游戏前

Vitality:100

Attack:0

Defence:100

战斗结束后

Vitality:0

Attack:100

Defence:0

恢复战斗前状态

Vitality:100

Attack:0

Defence:100


备忘录模式,保存某一时刻的状态,在之后的某一刻使用其来恢复到保存的状态。