class Memento { private String state; public Memento(Originator o){ state = o.state; } public void setState(String state){ this.state=state; } public String getState(){ return this.state; } }使用场景
public class Role{ private int bloodFlow;//血量 private int magicPoint;//蓝量 public Role(int bloodFlow,int magicPoint){//构造函数 this.bloodFlow = bloodFlow; this.magicPoint = magicPoint; } public int getBloodFlow() { return bloodFlow; } public void setBloodFlow(int bloodFlow) { this.bloodFlow = bloodFlow; } public int getMagicPoint() { return magicPoint; } public void setMagicPoint(int magicPoint) { this.magicPoint = magicPoint; } //展示用户当前状态 public void display(){ System.out.println("用户当前状态:"); System.out.println("血量:" + getBloodFlow() + ";蓝量:" + getMagicPoint()); } //保持存档、当前状态 public Memento saveMemento(){ return new Memento(getBloodFlow(), getMagicPoint());//返回一个备忘录对象 } //恢复存档 public void restoreMemento(Memento memento){ this.bloodFlow = memento.getBloodFlow(); this.magicPoint = memento.getMagicPoint(); } }
public class Memento { private int bloodFlow; private int magicPoint; public int getBloodFlow() { return bloodFlow; } public void setBloodFlow(int bloodFlow) { this.bloodFlow = bloodFlow; } public int getMagicPoint() { return magicPoint; } public void setMagicPoint(int magicPoint) { this.magicPoint = magicPoint; } public Memento(int bloodFlow,int magicPoint){ this.bloodFlow = bloodFlow; this.magicPoint = magicPoint; } }
public class Caretaker { Memento memento;//持有一个备忘录引用 public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }4、编写客户端:Client.java
public class Client { public static void main(String[] args) { //打BOSS之前:血、蓝全部满值 Role role = new Role(100, 100); System.out.println("----------挑战BOSS之前----------"); role.display(); //用负责人保持进度 Caretaker caretaker = new Caretaker(); caretaker.memento = role.saveMemento(); //挑战BOSS,快gome Over了 role.setBloodFlow(20); role.setMagicPoint(20); System.out.println("----------挑战BOSS之后----------"); role.display(); //利用负责人恢复存档 role.restoreMemento(caretaker.getMemento()); System.out.println("----------恢复之后----------"); role.display(); } }
----------挑战BOSS之前---------- 用户当前状态: 血量:100;蓝量:100 ----------挑战BOSS之后---------- 用户当前状态: 血量:20;蓝量:20 ----------恢复之后---------- 用户当前状态: 血量:100;蓝量:100
三、总结
1、备忘录模式可以实现在不破坏封装的前提下,捕获一个类的内部状态,并且在该对象之外保存该对象的状态,保证该对象能够恢复到历史的某个状态。