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

备忘录模式

恢复之前状态

1.一个游戏,里面有个创建备忘录的方法,该方法存储当前游戏进度到备忘录中,并且返回备忘录.另外一个是拿到备忘录,将备忘录的数据恢复到游戏中.

public class Game {
    int gamelv;
    String name;
    String age;
    String password;

    public Game(int gamelv, String name, String age) {
        this.gamelv = gamelv;
        this.name = name;
        this.age = age;
    }

    public Game() {
    }

    public Memento createMemento() {
        return new Memento(this.gamelv,this.name,this.age);
    }

    public void restoreMemento(Memento memento) {
        this.gamelv = memento.gamelv;
        this.name = memento.name;
        this.age = memento.age;
    }

    public int getGamelv() {
        return gamelv;
    }

    public void setGamelv(int gamelv) {
        this.gamelv = gamelv;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

2.备忘录的类 

public class Memento {
    int gamelv;
    String name;
    String age;


    public Memento(int gamelv, String name, String age) {
        this.gamelv = gamelv;
        this.name = name;
        this.age = age;
    }

    public int getGamelv() {
        return gamelv;
    }

    public void setGamelv(int gamelv) {
        this.gamelv = gamelv;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

3.备忘录管理者 ,一个是获取当前管理者手里的备忘录,另外一个是将游戏创建的备忘录保存到管理者手中.

public class Caretaker {
    //备忘录对象
    private Memento memento;

    public Memento getMemento() {
        return memento;
    }
    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}

4.测试

public class Test {
    public void test() {
        Game game = new Game();
        game.setAge("11");

        Caretaker caretaker = new Caretaker();  //备忘录管理者

        caretaker.setMemento(game.createMemento());  //保存Game状态

        game.setGamelv(22);  //改变game状态

        game.restoreMemento(caretaker.getMemento());  //恢复game状态

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值