备忘录模式 Memento Pattern
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
小明开披萨外卖店攒了一点钱,开始动心想开一家真正的西餐厅,不过这是一笔大投资,弄不好会赔掉全部积蓄,还要搭上时间。
如果人生失败后能重来就好了。
正在纠结的时候,忽然天上来了一位仙人,对他说:
孩子,你尽管大胆的去尝试吧,如果失败了,我来帮你回到现在。嗯,让我先保存一份你现在的状态。
小明于是把自己的年龄和存款数写在记事本上交给神仙保管,开开心心去筹备餐厅了。
UML:
代码:
public class Memento {
private int money;
private int age;
public Memento(int money, int age) {
this.money = money;
this.age = age;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class XiaoMing {
private int money;
private int age;
public XiaoMing(int money, int age) {
this.money = money;
this.age = age;
}
public Memento createMemento() {
return new Memento(money, age);
}
public void restoreMemento(Memento memento) {
this.money = memento.getMoney();
this.age = memento.getAge();
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Immortal {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
客户端:
public class Client {
public static void main(String[] args) {
XiaoMing xiaoMing = new XiaoMing(1000000, 35);
Memento memento = xiaoMing.createMemento();
Immortal immortal = new Immortal();
immortal.setMemento(memento);
System.out.println("现在的状态: 年龄 " + xiaoMing.getAge() + " 存款 " + xiaoMing.getMoney());
xiaoMing.setMoney(-100000);
xiaoMing.setAge(40);
System.out.println("5年后餐厅亏损: 年龄 " + xiaoMing.getAge() + " 存款 " + xiaoMing.getMoney());
xiaoMing.restoreMemento(immortal.getMemento());
System.out.println("神仙帮小明恢复到从前: 年龄 " + xiaoMing.getAge() + " 存款 " + xiaoMing.getMoney());
}
}
现在的状态: 年龄 35 存款 1000000
5年后餐厅亏损: 年龄 40 存款 -100000
神仙帮小明恢复到从前: 年龄 35 存款 1000000
5年后,小明看着每天门可罗雀的餐厅非常苦闷,不仅存款用光,还借了很多钱,而且5年的时光就这么没了。他忽然想起了之前和仙人的约定。。。
突然,小明醒了过来,赶紧上网查了查,还是2019年,自己还是35岁,存款也没有少。原来是一场噩梦。
过了两天,小明又开始纠结了,要不要开家餐厅呢?