备忘录模式

备忘录模式

备忘录(Memento)模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便以后当需要时能将该对象恢复到原先保存的状态。该模式又叫快照模式。

案例

每次玩游戏时从服务器读取存档,退出后保存存档

存档类:

java 复制代码
public class GameRecoder {
    Integer id;
    Integer level;

    public GameRecoder(Integer id, Integer level) {
        this.id = id;
        this.level = level;
    }

    @Override
    public String toString() {
        return "GameRecoder{" +
                "id=" + id +
                ", level=" + level +
                '}';
    }
}

服务器:

java 复制代码
public class GameServer {
    Map<Integer,GameRecoder> map = new HashMap<>();
    int cur = 0;

    {
        cur++;
        GameRecoder gameRecoder = new GameRecoder(cur, 1);
        map.put(cur,gameRecoder);

    }

    public void addRecord(Integer level){
        cur++;
        GameRecoder gameRecoder = new GameRecoder(cur, level);
        map.put(cur,gameRecoder);
        System.out.println("添加存档:"+gameRecoder);
    }

    public GameRecoder getRecord(){
        System.out.println("读取存档:"+map.get(cur));
        return map.get(cur);
    }
}

游戏:

java 复制代码
public class MyGame {
    private Integer level;

    GameServer server = new GameServer();

    public void play(){
        GameRecoder record = server.getRecord();
        level = record.level;
        System.out.println("开始游戏,当前等级:"+level);
        level++;
    }

    // 存档
    private void save(){
        server.addRecord(level);
    }

    public void exit(){
        System.out.println("退出游戏");
        save();
    }
}

测试:

java 复制代码
public class Main {
    public static void main(String[] args) {
        MyGame myGame = new MyGame();
        myGame.play();

        myGame.exit();
        myGame.play();
    }
}
相关推荐
Evand J21 小时前
【MATLAB例程】【空地协同】UAV辅助的UGV协同定位,无人机辅助地面无人车定位,带滤波,附MATLAB代码下载链接
开发语言·matlab·无人机·无人车·uav·协同定位·ugv
chao18984421 小时前
基于MATLAB实现多变量高斯过程回归(GPR)
开发语言·matlab·回归
ytttr8731 天前
隐马尔可夫模型(HMM)MATLAB实现范例
开发语言·算法·matlab
天远Date Lab1 天前
Python实战:对接天远数据手机号码归属地API,实现精准用户分群与本地化运营
大数据·开发语言·python
listhi5201 天前
基于Gabor纹理特征与K-means聚类的图像分割(Matlab实现)
开发语言·matlab
野生的码农1 天前
码农的妇产科实习记录
android·java·人工智能
qq_433776421 天前
【无标题】
开发语言·php
Davina_yu1 天前
Windows 下升级 R 语言至最新版
开发语言·windows·r语言
阿珊和她的猫1 天前
IIFE:JavaScript 中的立即调用函数表达式
开发语言·javascript·状态模式
毕设源码-赖学姐1 天前
【开题答辩全过程】以 高校人才培养方案管理系统的设计与实现为例,包含答辩的问题和答案
java