设计模式 --- 备忘录模式

1.定义

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

2.使用场景

1)需要保存一个对象在某一个时刻的状态或部分状态

2)如果用一个接口来让其他对象得到这些状态,将会暴露对象的实现细节并破坏对象的封装性,一个对象不希望外界直接访问内部状态,通过中间对象可以间接访问其内部对象。

3.简单实现

模拟一个游戏存档的功能。

//定义一个游戏类
class Game{
    private int lifeValue = 100; //游戏人物生命值
    private int mLevel = 1; //游戏人物等级
    private String mWeapon = "新手剑"; //人物装备

    //模拟玩游戏
    public void  playGame(){
        System.out.println("碰见了一只 野猪 ! 奋力搏斗中...");
        System.out.println("你损失了 -10HP !");
        lifeValue -= 10;
        System.out.println(this.toString());
        System.out.println("你击杀了 野猪 ! 升级!");
        mLevel += 1;
        System.out.println(this.toString());
        System.out.println("野猪 爆出了 屠龙宝刀! 装备中...");
        mWeapon = "屠龙宝刀";
        System.out.println(this.toString());
    }

    //退出游戏
    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.lifeValue = lifeValue;
        memoto.mLevel = mLevel;
        memoto.mWeapon = mWeapon;
        return memoto;
    }

    //恢复游戏
    public void reStore(Memoto memoto){
        System.out.println("--------------------------------------");
        System.out.println("存档读取中...");
        this.lifeValue = memoto.lifeValue;
        this.mLevel = memoto.mLevel;
        this.mWeapon = memoto.mWeapon;
        System.out.println("当前属性:" + this.toString());
        System.out.println("--------------------------------------");
    }

    @Override
    public String toString() {
        return "[ Level:"+ this.mLevel +" Life:"+ lifeValue+" Weapone:"+ mWeapon+" ]";
    }
}

//创建一个备忘录
class Memoto{
    public int lifeValue;
    public int mLevel ;
    public String mWeapon ;

    @Override
    public String toString() {
        return "[ Level:"+ this.mLevel +" Life:"+ lifeValue+" Weapone:"+ mWeapon+" ]";
    }
}

//备忘录操作者
class Caretaker{
    Memoto memoto;
    //存档
    public void archive(Memoto memoto){
        this.memoto = memoto;
    }
    //读档
    public Memoto getMemoto(){
        return memoto;
    }
}

public class OriginatorMode {

    public static void main(String[] args){
        //构建游戏对象
        Game game = new Game();
        //打游戏
        game.playGame();
        //游戏存档
        Caretaker caretaker = new Caretaker();
        caretaker.archive(game.createMemoto());
        //退出游戏
        game.quit();
        //重新恢复游戏 重新新建一个对象
        Game gameTwo = new Game();
        gameTwo.reStore(caretaker.getMemoto());

    }
}

输出:

4.小结

优点:

1.给用户提供了一种可以恢复状态的机制,比较方便地回到某个历史状态;

2.实现了信息的封装,使用户不需要关心状态的保存细节。

缺点:

资源消耗,如果类的成员变量太多,会占用较大资源,而且每一次保存会消耗一定的内存资源。

猜你喜欢

转载自blog.csdn.net/huxing0215/article/details/84304415