定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到先前保存的状态。
类图:
说明:Originator表示原发器,它创建备忘录并存储其当前内部状态,还可以使用备忘录来恢复内部状态;Memento表示备忘录,它存储原发器Originator的内部状态,并更具原发器来决定保存哪些内部状态,同时它还通过一些机制来防止原发器以外的其他对象访问备忘录,理想的情况是只允许生成本备忘录的那个原发器访问本备忘录的内部状态;Caretaker表示负责人,它负责保存好备忘录,但不能对备忘录的内容进行操作或检查。
优点:
使用备忘录模式,可以避免暴露一些只应由原发器管理缺又必须存储在原发器之外的信息,而且能够在对象需要时恢复到先前状态。
缺点:
使用备忘录可能代价很高。如果原发器在生成备忘录时必须复制并存储大量的信息,或者客户非常频繁第创建备忘录和恢复原发器状态,可能会导致非常大的开销。
适用环境:如下实例
实例场景:备忘录模式之游戏恢复点设置,某模拟战争游戏为了给我哪家提供更好的用户体验,在游戏过程中可以设置一个恢复点,记录当前游戏场景,如果在后续游戏中玩家角色“不幸死亡”,可以返回到当前场景,从所设恢复点开始重新游戏。
实例类图:
实例代码:
/**
* 游戏场景类:原发器
* @author fly
*
*/
public class GameScene {
private String scene;
private int lifeValue;
public String getScene() {
return scene;
}
public void setScene(String scene) {
this.scene = scene;
}
public int getLifeValue() {
return lifeValue;
}
public void setLifeValue(int lifeValue) {
this.lifeValue = lifeValue;
}
public void restore(SceneMemento m){
this.scene = m.getScene();
this.lifeValue = m.getLifeValue();
}
public SceneMemento save(){
return new SceneMemento(this.scene, this.lifeValue);
}
public void display(){
System.out.print("当前游戏场景为:"+this.scene+",");
System.out.println("你还有"+this.lifeValue+"几条命");
}
}
/**
* 场景备忘录:备忘录
* @author fly
*
*/
public class SceneMemento {
private String scene;
private int lifeValue;
public SceneMemento(String scene,int lifeValue) {
// TODO Auto-generated constructor stub
this.scene = scene;
this.lifeValue = lifeValue;
}
public String getScene() {
return scene;
}
public void setScene(String scene) {
this.scene = scene;
}
public int getLifeValue() {
return lifeValue;
}
public void setLifeValue(int lifeValue) {
this.lifeValue = lifeValue;
}
}
/**
* 负责人
* @author fly
*
*/
public class Caretaker {
private SceneMemento memento;
public SceneMemento getSceneMemento() {
return this.memento;
}
public void setSceneMemento(SceneMemento memento) {
this.memento = memento;
}
}
/**
* 客户端测试类
* @author fly
*
*/
public class Client {
public static void main(String[] args) {
GameScene scene = new GameScene();
Caretaker ct = new Caretaker();
scene.setScene("无名胡");
scene.setLifeValue(3);
System.out.println("原始状态");
scene.display();
ct.setSceneMemento(scene.save());
System.out.println("-----------------------------------------");
scene.setScene("魔鬼窟");
scene.setLifeValue(0);
System.out.println("牺牲状态:");
scene.display();
System.out.println("-----------------------------------------");
scene.restore(ct.getSceneMemento());
System.out.println("恢复到原始状态");
scene.display();
System.out.println("-----------------------------------------");
}
}
//运行结果: