备忘录模式

备忘录模式

备忘录(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();
    }
}
相关推荐
huohaiyu2 分钟前
synchronized (Java)
java·开发语言·安全·synchronized
梵得儿SHI2 分钟前
Java 工具类详解:Arrays、Collections、Objects 一篇通关
java·工具类·collections·arrays·objects
_OP_CHEN9 分钟前
C++基础:(九)string类的使用与模拟实现
开发语言·c++·stl·string·string类·c++容器·stl模拟实现
熊小猿10 分钟前
Spring Boot 的 7 大核心优势
java·spring boot·后端
摸鱼的老谭12 分钟前
Java学习之旅第二季-13:方法重写
java·学习·方法重写
云灬沙12 分钟前
IDEA2025无法更新使用Terminal控制台
java·intellij-idea·idea·intellij idea
Yield & Allure13 分钟前
IDEA在plugins里搜不到mybatisx插件的解决方法
java·ide·intellij-idea
yunmi_17 分钟前
安全框架 SpringSecurity 入门(超详细,IDEA2024)
java·spring boot·spring·junit·maven·mybatis·spring security
孤独斗士18 分钟前
解决Intellij IDEA控制台,logger.info(),system.out.println()等中文乱码问题
java·ide·intellij-idea
shepherd11122 分钟前
JDK 8钉子户进阶指南:十年坚守,终迎Java 21升级盛宴!
java·后端·面试