如何实现 c++++ 中的备忘录设计模式?创建 originator 类,它存储对象的状态;创建 memento 类,它存储 originator 状态的快照;创建 caretaker 类,它负责存储和管理 memento。
备忘录设计模式是一种行为设计模式,它允许您存储和还原一个对象的内部状态。这对于管理复杂对象的快照或在事务中撤消操作非常有用。
实现
在 C++ 中实现备忘录设计模式涉及创建三个类:
立即学习“C++免费学习笔记(深入)”;
代码示例
以下是 C++ 中备忘录设计模式的示例实现:
#include <iostream> #include <string> #include <memory> class Originator { public: Originator(const std::string& state) : state_(state) {} void SetState(const std::string& state) { state_ = state; } std::shared_ptr<Memento> CreateMemento() { return std::make_shared<Memento>(state_); } void RestoreMemento(const std::shared_ptr<Memento>& memento) { state_ = memento->GetState(); } void PrintState() { std::cout << "Current state: " << state_ << "\n"; } private: std::string state_; }; class Memento { public: Memento(const std::string& state) : state_(state) {} std::string GetState() const { return state_; } private: std::string state_; }; class Caretaker { public: Caretaker() {} void SetMemento(const std::shared_ptr<Memento>& memento) { memento_ = memento; } std::shared_ptr<Memento> GetMemento() const { return memento_; } private: std::shared_ptr<Memento> memento_; }; int main() { // 创建 Originator 并设置其状态 Originator originator("Initial state"); originator.PrintState(); // 创建 Caretaker 并存储 Originator 的 Memento Caretaker caretaker; caretaker.SetMemento(originator.CreateMemento()); // 修改 Originator 的状态 originator.SetState("New state"); originator.PrintState(); // 从 Memento 恢复 Originator 的状态 originator.RestoreMemento(caretaker.GetMemento()); originator.PrintState(); return 0; }
实战案例
备忘录设计模式可用于实现以下功能:
以上就是如何在C++中实现备忘录设计模式?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号