在开发过程中,我们可能会遇到保存对象目前的状态,到必要的时候再进行恢复的需求,这类似于数据库中的后援副本,到出现故障时数据库可以回到转储时的状态
备忘录模式的示例
在一般软件的开发中,备忘录模式是使用得比较少的设计模式,但是在游戏开发过程中,备忘录模式是使用得很频繁的,这里就举一个小游戏的例子
游戏类
public class Mario {
private int checkPoint = 1;
private int lifeValue = 100;
private String state = "正常";
public void play() {
System.out.println("现在在:" + String.format("第%d关", checkPoint));
lifeValue -= 10;
System.out.println("过关!");
checkPoint ++ ;
System.out.println("现在是" + String.format("第%d关",checkPoint));
}
public void quit() {
System.out.println("退出前的游戏属性:" + this.toString());
}
public Memoto createMemoto () {
Memoto memoto = new Memoto();
memoto.checkPoint = checkPoint;
memoto.state = state;
memoto.lifeValue = lifeValue;
return memoto;
}
public void restore(Memoto memoto) {
this.checkPoint = memoto.checkPoint;
this.lifeValue = memoto.lifeValue;
this.state = memoto.state;
System.out.println("恢复后的游戏属性:" + this.toString());
}
@Override
public String toString() {
return "CheckPoint:" + checkPoint + ", LifeValue:" + lifeValue +", State:" + state;
}
}
备忘录类
public class Memoto {
public int checkPoint;
public int lifeValue;
public String state;
@Override
public String toString() {
return "CheckPoint:" + checkPoint + ", LifeValue:" + lifeValue +", State:" + state;
}
}
备忘录管理类
public class Caretaker {
Memoto memoto;
public void archive(Memoto memoto) {
this.memoto = memoto;
}
public Memoto getMemoto() {
return memoto;
}
}
使用示例
public class Main {
public static void main(String[] args) {
Mario mario = new Mario();
mario.play();
Caretaker caretaker = new Caretaker();
caretaker.archive(mario.createMemoto());
mario.quit();
Mario mario1 = new Mario();
mario1.restore(caretaker.getMemoto());
}
}
结果如下:
当然,如果我们需要开发一个游戏,肯定是持久化存储与备忘录模式一起使用