软件设计 备忘录模式 Memento Pattern
作者:@kuaiquxie
作者的github:https://github.com/bitebita
本文为作者原创,如需转载,请注明出处:https://www.cnblogs.com/dzwj/p/17111695.html
程序虽然来源于生活,有时候也能高于生活,比如遗憾,在程序中就是能补救的。游戏中有存档和读档,设计模式中也有备忘录模式可以实现。
备忘录模式就是为程序提供了一个可回溯的时间节点,如果程序在运行过程中某一步出现了错误,就可以回到之前的某个被保存的节点上重新来过(就像艾克的大招)。平时编辑文本的时候,当编辑出现错误时,就需要撤回,此时只需要按下 Ctrl + Z 就可以回到上一步,这样大大方便了文本编辑。
其实备忘录模式在程序中的应用十分广泛,比如安卓程序在很多情况下都会重新加载 Activity
,实际上安卓中 Activity
的 onSaveInstanceState
和 onRestoreInstanceState
就是用到了备忘录模式,分别用于保存和恢复,这样就算重新加载也可以恢复到之前的状态。
1.学生为例的代码实现:
下面以学生学习为例介绍备忘录模式:
1、定义学生
public class Student {
/**
* 当前正在做的事
*/
private String currentThing;
/**
* 当前做的事完成百分比
*/
private int percentage;
/**
* 做事
* @param currentThing 当前正在做的事
*/
public void todo(String currentThing) {
this.currentThing = currentThing;
this.percentage = new Random().nextInt(100);
}
/**
* 保存当前状态
* @return 当前状态
*/
public State save() {
return new State(this.currentThing, this.percentage);
}
/**
* 重置状态
* @param state 状态
*/
public void restore(State state){
this.currentThing = state.getCurrentThing();
this.percentage = state.getPercentage();
}