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

news/2025/2/22 21:51:56/

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

#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/news/1574258.html

相关文章

在低功耗MCU上实现人工智能和机器学习

作者&#xff1a;Silicon Labs 人工智能&#xff08;AI&#xff09;和机器学习&#xff08;ML&#xff09;技术不仅正在快速发展&#xff0c;还逐渐被创新性地应用于低功耗的微控制器&#xff08;MCU&#xff09;中&#xff0c;从而实现边缘AI/ML解决方案。这些MCU是许多嵌入式…

html中iframe标签 隐藏滚动条

iframe 隐藏滚动条 1. 直接隐藏的策略&#xff1a; frame 有个属性 scrolling&#xff0c;直接设置 scrolling‘no’ 即可隐藏 scrollbar。这样iframe就不能滚动了。 <iframe src"https://www.baidu.com/" scrolling"no"></iframe>2. 修改 i…

使用 Docker 部署 Apache Spark 集群教程

简介 Apache Spark 是一个强大的统一分析引擎&#xff0c;用于大规模数据处理。本文将详细介绍如何使用 Docker 和 Docker Compose 快速部署一个包含一个 Master 节点和两个 Worker 节点的 Spark 集群。这种方法不仅简化了集群的搭建过程&#xff0c;还提供了资源隔离、易于扩…

Jmeter进阶篇(34)如何解决jmeter.save.saveservice.timestamp_format=ms报错?

问题描述 今天使用Jmeter完成压测执行,然后使用命令将jtl文件转换成html报告时,遇到了报错! 大致就是说jmeter里定义了一个jmeter.save.saveservice.timestamp_format=ms的时间格式,但是jtl文件中的时间格式不是标准的这个ms格式,导致无法正常解析。对于这个问题,有如下…

网络安全:DeepSeek已经在自动的挖掘漏洞

大家好,我是AI拉呱,一个专注于人工智领域与网络安全方面的博主,现任资深算法研究员一职,兼职硕士研究生导师;热爱机器学习和深度学习算法应用,深耕大语言模型微调、量化、私域部署。曾获多次获得AI竞赛大奖,拥有多项发明专利和学术论文。对于AI算法有自己独特见解和经验…

微软宣布 Windows 11 将不再免费升级:升级需趁早

大家都知道如果你现在是Windows 10 系统&#xff0c;其实可以免费升级到正版 Windows 11&#xff0c;只要你的电脑配置满足 TPM2.0要求。 而最近微软已经公布了 Windows 10 的最后支持时间&#xff0c;也就是今年10月14日&#xff0c;在这之后微软将不再对Windows 10负责&#…

Vmware虚拟机Ubantu安装Docker、k8s、kuboard

准备工作: 切换用户&#xff1a;su root关闭防火墙: sudo ufw diasble关闭swap: systemctl stop swap.target systemctl status swap.target systemctl disable swap.target #开机禁用 systemctl stop swap.img.swap systemctl status swap.img.swap关闭虚拟交换分区 vim /…

微软Win11新动态:官方“换机助手”曝光,PC数据迁移或迎全新体验

目录 微软入局数据迁移领域,第三方工具或面临挑战 无缝迁移体验:近距离传输与OTP验证 模拟图仅为概念设计,最终功能或存变数 发布时间未定,Insider用户或率先体验 总结 微软在近期发布了Windows 11 Insider Beta频道的最新版本Build 22635.4945。尽管此次更新并未引入重…