C++ 设计模式-备忘录模式

server/2025/2/23 11:35:53/

游戏存档实现,包括撤销/重做、持久化存储、版本控制和内存管理

#include <iostream>
#include <memory>
#include <deque>
#include <stack>
#include <chrono>
#include <fstream>
#include <sstream>
#include <ctime>// ================ 1. 增强版备忘录类 ================
class GameMemento {
private:const int level;const int health;const std::string weapon;const std::chrono::system_clock::time_point timestamp;friend class GameCharacter;public:GameMemento(int lv, int hp, std::string wp, std::chrono::system_clock::time_point ts): level(lv), health(hp), weapon(std::move(wp)), timestamp(ts) {}// 序列化为字符串std::string serialize() const {std::time_t ts = std::chrono::system_clock::to_time_t(timestamp);std::stringstream ss;ss << level << "," << health << "," << weapon << "," << ts;return ss.str();}// 从字符串反序列化static std::unique_ptr<GameMemento> deserialize(const std::string& data) {std::stringstream ss(data);int lv, hp;std::string wp;time_t ts;char comma;ss >> lv >> comma >> hp >> comma;std::getline(ss, wp, ',');ss >> ts;return std::make_unique<GameMemento>(lv, hp, wp, std::chrono::system_clock::from_time_t(ts));}void print() const {auto ts = std::chrono::system_clock::to_time_t(timestamp);char buffer[26];strftime(buffer, sizeof(buffer), "%a %b %d %H:%M:%S %Y", std::localtime(&ts));std::cout << "Lv." << level << " HP:" << health<< " Weapon:" << weapon << " (" << buffer << ")\n";}
};// ================ 2. 游戏角色类 ================
class GameCharacter {
private:int level = 1;int health = 100;std::string weapon = "Fist";public:void levelUp() { level++; health += 20; }void takeDamage(int dmg) { health -= dmg; }void equipWeapon(std::string wp) { weapon = std::move(wp); }std::unique_ptr<GameMemento> save() const {return std::make_unique<GameMemento>(level, health, weapon,std::chrono::system_clock::now());}void load(const GameMemento& memento) {level = memento.level;health = memento.health;weapon = memento.weapon;}void status() const {std::cout << "Current State: Lv." << level<< " HP:" << health<< " Weapon:" << weapon << "\n";}
};// ================ 3. 增强版存档管理器 ================
class SaveManager {
private:std::deque<std::unique_ptr<GameMemento>> undoStack;  // 使用deque方便限制数量std::stack<std::unique_ptr<GameMemento>> redoStack;  // 重做栈const size_t MAX_SAVES = 5;  // 最大存档数量void trimHistory() {while (undoStack.size() > MAX_SAVES) {undoStack.pop_front();  // 移除最旧的存档}}public:// 保存新状态void saveState(const GameCharacter& character) {undoStack.push_back(character.save());redoStack = std::stack<std::unique_ptr<GameMemento>>(); // 清空重做栈trimHistory();}// 撤销bool undo(GameCharacter& character) {if (undoStack.size() < 2) return false;redoStack.push(std::move(undoStack.back()));undoStack.pop_back();character.load(*undoStack.back());return true;}// 重做bool redo(GameCharacter& character) {if (redoStack.empty()) return false;character.load(*redoStack.top());undoStack.push_back(std::move(redoStack.top()));redoStack.pop();return true;}// 保存到文件bool saveToFile(const std::string& filename) const {std::ofstream file(filename);if (!file) return false;for (const auto& memento : undoStack) {file << memento->serialize() << "\n";}return true;}// 从文件加载bool loadFromFile(const std::string& filename, GameCharacter& character) {std::ifstream file(filename);if (!file) return false;undoStack.clear();redoStack = std::stack<std::unique_ptr<GameMemento>>();std::string line;while (std::getline(file, line)) {auto memento = GameMemento::deserialize(line);if (memento) {undoStack.push_back(std::move(memento));}}if (!undoStack.empty()) {character.load(*undoStack.back());}return true;}// 显示版本历史void showHistory() const {std::cout << "\n=== Version History (" << undoStack.size() << "/"<< MAX_SAVES << ") ===\n";int i = 1;for (const auto& memento : undoStack) {std::cout << "Version " << i++ << ": ";memento->print();}}
};// ================ 使用示例 ================
int main() {GameCharacter hero;SaveManager saveManager;// 初始状态hero.status();saveManager.saveState(hero);// 查看历史版本saveManager.showHistory();// 进行一系列操作hero.levelUp();hero.equipWeapon("Sword");saveManager.saveState(hero);hero.takeDamage(30);saveManager.saveState(hero);hero.levelUp();hero.equipWeapon("Axe");saveManager.saveState(hero);// 查看历史版本saveManager.showHistory();// 持久化存储saveManager.saveToFile("game_save.txt");// 连续撤销两次std::cout << "=== Undo x2 ===\n";saveManager.undo(hero);saveManager.undo(hero);hero.status();// 重做一次std::cout << "=== Redo x1 ===\n";saveManager.redo(hero);hero.status();// 从文件加载GameCharacter loadedHero;SaveManager loadManager;loadManager.loadFromFile("game_save.txt", loadedHero);std::cout << "=== Loaded Character ===\n";loadedHero.status();loadManager.showHistory();hero.takeDamage(-30);saveManager.saveState(hero);hero.status();// 查看历史版本saveManager.showHistory();return 0;
}

功能实现说明:

  1. 撤销/重做系统

    • 使用双栈结构(undoStack + redoStack)
    • undo() 保留最近两个状态以实现状态对比
    • 每次保存时清空重做栈
  2. 持久化存储

    • 使用CSV格式存储:level,health,weapon,timestamp
    • 支持从文件恢复完整历史记录
  3. 版本控制

    • 每个存档包含精确到秒的时间戳
    • showHistory() 显示带时间的版本信息
  4. 内存优化

    • 限制最大存档数量(MAX_SAVES = 5)
    • 自动移除最早的存档
  5. 附加功能

    • 版本历史浏览
    • 完整的异常安全设计
    • 使用现代C++特性(chrono时间库、智能指针等)

执行结果示例:

Current State: Lv.1 HP:100 Weapon:Fist=== Version History (1/5) ===
Version 1: Lv.1 HP:100 Weapon:Fist (Fri Feb 21 12:10:21 2025)=== Version History (4/5) ===
Version 1: Lv.1 HP:100 Weapon:Fist (Fri Feb 21 12:10:21 2025)
Version 2: Lv.2 HP:120 Weapon:Sword (Fri Feb 21 12:10:21 2025)
Version 3: Lv.2 HP:90 Weapon:Sword (Fri Feb 21 12:10:21 2025)
Version 4: Lv.3 HP:110 Weapon:Axe (Fri Feb 21 12:10:21 2025)
=== Undo x2 ===
Current State: Lv.2 HP:120 Weapon:Sword
=== Redo x1 ===
Current State: Lv.2 HP:90 Weapon:Sword
=== Loaded Character ===
Current State: Lv.3 HP:110 Weapon:Axe=== Version History (4/5) ===
Version 1: Lv.1 HP:100 Weapon:Fist (Fri Feb 21 12:10:21 2025)
Version 2: Lv.2 HP:120 Weapon:Sword (Fri Feb 21 12:10:21 2025)
Version 3: Lv.2 HP:90 Weapon:Sword (Fri Feb 21 12:10:21 2025)
Version 4: Lv.3 HP:110 Weapon:Axe (Fri Feb 21 12:10:21 2025)
Current State: Lv.2 HP:120 Weapon:Sword=== Version History (4/5) ===
Version 1: Lv.1 HP:100 Weapon:Fist (Fri Feb 21 12:10:21 2025)
Version 2: Lv.2 HP:120 Weapon:Sword (Fri Feb 21 12:10:21 2025)
Version 3: Lv.2 HP:90 Weapon:Sword (Fri Feb 21 12:10:21 2025)
Version 4: Lv.2 HP:120 Weapon:Sword (Fri Feb 21 12:10:21 2025)

http://www.ppmy.cn/server/170119.html

相关文章

算法【博弈类问题】

本文最开始讲解一些常见博弈类问题如巴什博弈(Bash)、尼姆博弈(Nim)、斐波那契博弈(Fibonacci)、威佐夫博弈(Wythoff)。通过这些讲解会发现&#xff0c;这些博弈问题在考场上要临时想清楚是不太可能的&#xff0c;所以需要后面的内容即SG函数、SG定理的内容&#xff0c;大多数博…

(安全防御)DNS透明代理

拓扑需求 配置步骤 1.完成防火墙基本接口配置 2.创建服务端的链路接口 3.配置虚拟DNS服务器&#xff0c;以及真是DNS服务器信息 slb enable 开启负载均衡功能 slb进入服务器负载均衡配置视图 设置真实服务器IP地址 端口 创建虚拟服务器组 设置虚拟ip地址 关联真实服务器组 …

OpenFeign 实现远程调用

1. 问题引入 在前面写的代码中&#xff0c;通过使用RestTemplate来实现远程调用&#xff0c;但是这种方式还是存在一些问题 需要拼接 URL&#xff0c;灵活性高&#xff0c;但是 URL 复杂时容易写错代码可读性差 而 OpenFeign 就解决了上述问题&#xff0c;OpenFeign 是一个声…

MySQL 日志

MySQL 日志 慢查询日志(Slow query log) 慢查询⽇志由执⾏时间超过系统变量 long_query_time 指定的秒数的SQL语句组成&#xff0c;并且检 查的⾏数⼤于系统变量 min_examined_row_limit 指定值。被记录的慢查询需要进⾏优化&#xff0c; 可以使⽤mysqldumpslow客⼾端程序对慢…

rk3588/3576板端编译程序无法运行视频推理

图片推理可以&#xff0c;但是视频不行&#xff0c;运行视频推理报错&#xff1a;segment fault. 我遇到的问题原因是ffmpeg安装有问题&#xff0c;可以先在板端运行&#xff1a;ffmpeg -version ffmpeg version 4.2.4-1ubuntu1.0firefly6 Copyright (c) 2000-2020 the FFmpe…

Android SDK封装打包流程详解

在Android开发中&#xff0c;SDK的封装和打包是将功能模块化并供其他开发者使用的常见需求。以下是Android SDK封装和打包的基本流程&#xff1a; 1. 创建Android Library模块 首先&#xff0c;你需要创建一个Android Library模块&#xff0c;而不是普通的Application模块。 在…

Ubuntu22.04 - gflags的安装和使用

目录 gflags 介绍gflags 安装gflags 使用 gflags 介绍 gflags 是Google 开发的一个开源库&#xff0c;用于 C应用程序中命令行参数的声明、定义和解析。gflags 库提供了一种简单的方式来添加、解析和文档化命令行标志(flags),使得程序可以根据不同的运行时配置进行调整。 它具…

告别卡关!XSS挑战之旅全关卡通关思路详解

XSS挑战之旅 XSS测试思路Level1Level2Level3Level4Level5Level6Level7Level8Level9Level10Level11Level12Level13Level14Level15Level16Level17Level18Level19Level20免责声明&#xff1a; XSS测试思路 确定输入输出点&#xff1a; 寻找URL参数、表单输入、HTTP头&#xff08;R…