备忘录模式(快照)
平时所用到的撤销功能
将一个对象的状态保存至一个临时容器中
如需撤销时从容器中取出
优点
- 在不破坏对象封装情况的前提下创建对象状态快照。
- 通过让负责人维护原发器状态历史记录来简化原发器代码。
缺点
- 过于频繁地创建备忘录, 程序将消耗大量内存。
- 必须完整跟踪原发器的生命周期, 这样才能销毁弃用的备忘录。
- 一些语言不能确保备忘录中的状态不被修改。
static class MyLife {
int age,money;
boolean marry;
public MyLife() {
this.age = 0;
this.marry = false;
this.money = 0;
System.out.println("角色新建完毕");
}
public void tenYearAfter() {
this.age += 10;
if (this.age >= 20) {
this.marry = true;
this.money = new Random().nextInt(1000000000);
}
}
void showLife() {
System.out.println(String.format(
"今年%d岁,%s,%s",
this.age,
this.marry ? "婚姻美满" : "尚未结婚",
this.marry ? "资产" + this.money + "元" : "还没工作"
));
}
private Memento saveLifeNode() {
return new TempLife(this.age, this.marry, this.money);
}
private void regret(Memento memento) {
TempLife tempLife = (TempLife) memento;
this.age = tempLife.age;
this.marry = tempLife.marry;
this.money = tempLife.money;
}
class TempLife implements Memento {
int age;
boolean marry;
int money;
public TempLife(int age, boolean marry, int money) {
this.age = age;
this.marry = marry;
this.money = money;
}
}
}
窄接口,保护快照属性安全
interface Memento {
}
备忘录管理
static class MementoCaretakers {
Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
结果
public static void main(String[] args) {
MyLife myLife = new MyLife();
MementoCaretakers caretakers = new MementoCaretakers();
caretakers.setMemento(myLife.saveLifeNode());
myLife.tenYearAfter();
myLife.showLife();
myLife.tenYearAfter();
myLife.showLife();
myLife.regret(caretakers.getMemento());
myLife.showLife();
}