设计模式中的撤销-备忘录模式

在开发过程中,我们可能会遇到保存对象目前的状态,到必要的时候再进行恢复的需求,这类似于数据库中的后援副本,到出现故障时数据库可以回到转储时的状态

备忘录模式的示例

在一般软件的开发中,备忘录模式是使用得比较少的设计模式,但是在游戏开发过程中,备忘录模式是使用得很频繁的,这里就举一个小游戏的例子

游戏类
public class Mario {
    private int checkPoint = 1;
    private int lifeValue = 100;
    private String state = "正常";

    public void play() {
        System.out.println("现在在:" + String.format("第%d关", checkPoint));
        lifeValue -= 10;
        System.out.println("过关!");
        checkPoint ++ ;
        System.out.println("现在是" + String.format("第%d关",checkPoint));
    }

    public void quit() {
        System.out.println("退出前的游戏属性:" + this.toString());
    }

    public Memoto createMemoto () {
        Memoto memoto = new Memoto();
        memoto.checkPoint = checkPoint;
        memoto.state = state;
        memoto.lifeValue = lifeValue;
        return memoto;
    }

    public void restore(Memoto memoto) {
        this.checkPoint = memoto.checkPoint;
        this.lifeValue = memoto.lifeValue;
        this.state = memoto.state;
        System.out.println("恢复后的游戏属性:" + this.toString());
    }

    @Override
    public String toString() {
        return "CheckPoint:" + checkPoint + ", LifeValue:" + lifeValue +", State:" + state;
    }
}
备忘录类
public class Memoto {
    public int checkPoint;
    public int lifeValue;
    public String state;

    @Override
    public String toString() {
        return "CheckPoint:" + checkPoint + ", LifeValue:" + lifeValue +", State:" + state;
    }
}
备忘录管理类
public class Caretaker {
    Memoto memoto;

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

    public Memoto getMemoto() {
        return memoto;
    }
}
使用示例
public class Main {
    public static void main(String[] args) {
        Mario mario = new Mario();
        mario.play();
        Caretaker caretaker = new Caretaker();
        caretaker.archive(mario.createMemoto());
        mario.quit();
        Mario mario1 = new Mario();
        mario1.restore(caretaker.getMemoto());
    }
}

结果如下:

1.PNG

当然,如果我们需要开发一个游戏,肯定是持久化存储与备忘录模式一起使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值