备忘录模式通过发起者、备忘录和管理者三者协作,实现对象状态的保存与恢复。发起者负责创建和恢复状态,备忘录存储状态且对外只读,管理者保存多个备忘录以支持撤销操作。示例中Editor为发起者,Memento保存文本状态,history用栈管理备忘录,实现撤销功能。该模式保持封装性,适用于实现撤销、快照等场景,需注意内存消耗与状态一致性。
在C++中,备忘录模式(Memento Pattern)是一种行为设计模式,用于在不破坏封装性的前提下,保存和恢复对象的内部状态。这种模式特别适用于实现撤销功能、快照保存或状态回滚。
备忘录模式的核心角色
该模式包含三个主要角色:
- 发起者(Originator):拥有内部状态,并能创建或恢复到某个状态的对象。
- 备忘录(Memento):用于保存发起者内部状态的只读对象,通常不允许外部修改其内容。
- 管理者(Caretaker):负责保存和管理多个备忘录,但不查看或操作其内容。
基本实现结构
下面是一个简洁的C++示例,展示如何使用备忘录模式保存和恢复对象状态:
#include <iostream> #include <string> #include <stack> // 备忘录类:保存状态 class Memento { std::string state; public: Memento(const std::string& s) : state(s) {} const std::string& getState() const { return state; } }; // 发起者类:管理自身状态 class Editor { std::string content; public: void setContent(const std::string& text) { content = text; } std::string getContent() const { return content; } // 创建备忘录(保存当前状态) Memento save() const { return Memento(content); } // 从备忘录恢复状态 void restore(const Memento& m) { content = m.getState(); } }; // 管理者类:保存多个备忘录(例如用于撤销) class History { std::stack<Memento> states; public: void push(const Memento& m) { states.push(m); } Memento pop() { if (states.empty()) { throw std::runtime_error("No saved states"); } Memento m = states.top(); states.pop(); return m; } bool empty() const { return states.empty(); } };
使用示例:实现撤销功能
通过组合上述类,可以轻松实现文本编辑器的撤销操作:
立即学习“C++免费学习笔记(深入)”;
int main() { Editor editor; History history; editor.setContent("First version"); history.push(editor.save()); // 保存状态 editor.setContent("Second version"); history.push(editor.save()); // 保存状态 editor.setContent("Third version"); std::cout << "Current: " << editor.getContent() << "n"; // 撤销一次 if (!history.empty()) { editor.restore(history.pop()); std::cout << "After undo: " << editor.getContent() << "n"; } // 再次撤销 if (!history.empty()) { editor.restore(history.pop()); std::cout << "After second undo: " << editor.getContent() << "n"; } return 0; }
关键设计要点
使用备忘录模式时需要注意以下几点:
- 保持封装性:备忘录对象对外只提供状态读取接口,防止外部篡改。
- 性能考虑:频繁保存大对象状态可能消耗较多内存,可结合深拷贝/浅拷贝策略优化。
- 生命周期管理:确保备忘录与发起者状态一致性,避免悬空引用。
- 可扩展性:可通过引入版本号、时间戳等信息增强备忘录功能。
基本上就这些。备忘录模式通过分离状态存储与管理逻辑,使对象具备“后悔”能力,是实现撤销、重做、快照等功能的优雅方式。
评论(已关闭)
评论已关闭