在软件开发中,我们经常会遇到需要保存和恢复对象状态的场景。比如文本编辑器中的“撤销”功能、游戏中的“存档/读档”机制等。这时候,C++备忘录模式(Memento Pattern)就派上用场了!本文将带你从零开始理解并实现这个经典的设计模式,即使是编程小白也能轻松上手。
备忘录设计模式是一种行为型设计模式,它允许在不破坏封装性的前提下,捕获并外部化一个对象的内部状态,以便以后可以将该对象恢复到原先保存的状态。
备忘录模式主要涉及三个角色:

使用C++设计模式教程中介绍的备忘录模式有以下优点:
下面我们通过一个简单的文本编辑器示例来演示如何在 C++ 中实现备忘录模式。用户可以输入文本,并随时保存当前状态,之后可以恢复到之前保存的状态。
#include <iostream>#include <string>#include <vector>class Memento {private: std::string state;public: Memento(const std::string& s) : state(s) {} std::string getState() const { return state; }};class TextEditor {private: std::string content;public: void type(const std::string& text) { content += text; } void print() const { std::cout << "Current content: " << content << std::endl; } // 创建备忘录 Memento save() { return Memento(content); } // 恢复状态 void restore(const Memento& memento) { content = memento.getState(); }};class History {private: std::vector<Memento> history;public: void push(const Memento& memento) { history.push_back(memento); } Memento pop() { if (history.empty()) { throw std::runtime_error("No more history!"); } Memento last = history.back(); history.pop_back(); return last; } bool isEmpty() const { return history.empty(); }};int main() { TextEditor editor; History history; editor.type("Hello "); history.push(editor.save()); editor.type("World!"); editor.print(); // 输出: Current content: Hello World! editor.restore(history.pop()); editor.print(); // 输出: Current content: Hello return 0;}上面的代码展示了完整的备忘录模式实现:
Memento 类用于存储 TextEditor 的状态(即文本内容)。TextEditor 是 Originator,它提供 save() 方法创建备忘录,以及 restore() 方法从备忘录恢复状态。History 是 Caretaker,它管理多个备忘录(这里用栈结构实现),但不直接访问其内容。通过这种方式,我们实现了安全的状态保存与恢复机制,同时保持了良好的封装性。
备忘录模式适用于以下场景:
需要注意的是,备忘录可能会占用较多内存,尤其是当对象状态很大或保存次数很多时。因此,在实际项目中应考虑内存优化策略,例如只保存状态差异(增量备份)或限制历史记录数量。
通过本篇软件设计模式教程,你已经掌握了 C++ 备忘录模式的核心思想和实现方法。这种模式不仅实用,而且体现了面向对象设计中“高内聚、低耦合”的原则。希望你能将它灵活运用到自己的项目中!
如果你正在学习 C++ 设计模式,不妨多练习几个例子,加深理解。记住,设计模式不是银弹,而是解决特定问题的工具箱——合理使用才能事半功倍!
本文由主机测评网于2025-12-17发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025128892.html