备忘录模式

备忘录模式

备忘录(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();
    }
}
相关推荐
DuelCode18 分钟前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
浪裡遊18 分钟前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
优创学社222 分钟前
基于springboot的社区生鲜团购系统
java·spring boot·后端
幽络源小助理29 分钟前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
猴哥源码31 分钟前
基于Java+springboot 的车险理赔信息管理系统
java·spring boot
lzb_kkk1 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
YuTaoShao1 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
好开心啊没烦恼1 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
Dcs2 小时前
超强推理不止“大”——手把手教你部署 Mistral Small 3.2 24B 大模型
java
简佐义的博客2 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang