备忘录模式

1类图

这里写图片描述

2定义:

2.1 在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

3应用场景:

3.1 需要保存一个对象在某一时刻的状态或部分状态。
3.2 如果用一个接口来让其他对象得到这些状态,将会暴露对象的实现细节并破坏对象的封装性,一个对象不希望外界直接访问其内部状态,通过中间对象可以间接访问其内部状态。

4模拟类

public class CallofDuty {
    private int mCheckpoint = 1;
    private int mLifeValue = 100;
    private String mWeepon = "沙漠之鹰";

    public void play(){
        System.out.println("玩游戏:" + String.format("第%d关", mCheckpoint) + "奋斗杀敌中!");
        mLifeValue -= 10;
        System.out.println("进度升级了");
        mCheckpoint++;
        System.out.println("达到 " + String.format("第%d关",mCheckpoint));
    }
    public void quit(){
        System.out.println("-----------");
        System.out.println("退出当前的游戏属性 : " + this.toString());
        System.out.println("退出游戏");
        System.out.println("-----------");
    }

    public Memoto createMemoto(){
        Memoto memoto = new Memoto();
        memoto.mCheckpoint = mCheckpoint;
        memoto.mLifeValue = mLifeValue;
        memoto.mWeapon = mWeepon;
        return memoto;
    }

    public void restore(Memoto memoto){
        this.mCheckpoint = memoto.mCheckpoint;
        this.mLifeValue = memoto.mLifeValue;
        this.mWeepon = memoto.mWeapon;
        System.out.println("恢复后的游戏属性 : " + this.toString());
    }
    @Override
    public String toString() {
        return "CallofDuty [mCheckpoint=" + mCheckpoint + ", mLifeValue=" + mLifeValue + ", mWeepon=" + mWeepon + "]";
    }



}

5创建要保存的对象类

public class Memoto {
    public int mCheckpoint;
    public int mLifeValue;
    public String mWeapon;
    @Override
    public String toString() {
        return "Memoto [mCheckpoint=" + mCheckpoint + ", mLifeValue=" + mLifeValue + ", mWeapon=" + mWeapon + "]";
    }
}

6保存和回复类

public class Caretaker {
    Memoto memoto;
    public void archive(Memoto memoto){
        this.memoto = memoto;
    }

    public Memoto getMemoto() {
        return memoto;
    }
}

7测试

public class Client {
    public static void main(String[] args) {
        CallofDuty game = new CallofDuty();
        game.play();

        Caretaker caretaker = new Caretaker();
        caretaker.archive(game.createMemoto());
        game.quit();
        CallofDuty newGame = new CallofDuty();
        newGame.restore(caretaker.getMemoto());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值