重温设计模式之备忘录模式

备忘录模式  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岁,存款也没有少。原来是一场噩梦。

过了两天,小明又开始纠结了,要不要开家餐厅呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值