C++ 设计模式:备忘录模式(Memento Pattern)

链接:C++ 设计模式
链接:C++ 设计模式 - 状态模式

备忘录模式(Memento Pattern)是一种行为设计模式,它允许在不破坏封装性的前提下捕获和恢复对象的内部状态。这个模式在需要保存和恢复对象状态的场景中非常有用,例如实现撤销操作。

1.问题分析

在开发中,有时需要保存对象的状态,以便在需要时恢复到之前的状态。这种需求在撤销/重做操作、游戏存档、编辑器状态恢复等场景中尤为常见。

备忘录模式通过将对象的状态封装在一个独立的备忘录对象中,实现了状态的保存和恢复,同时保持了对象的封装性。

2.实现步骤

  1. 定义备忘录类:存储对象的内部状态,
  2. 定义发起人类:负责创建和恢复备忘录。
  3. 定义管理者类:负责保存和管理备忘录对象。
  4. 客户端代码:实现保存状态到备忘录和从备忘录恢复状态。

3.代码示例

3.1.定义备忘录类

cpp 复制代码
// Memento类,负责存储机器人的状态
class Memento {
 public:
  Memento(int x, int y, const std::string& state) : x_(x), y_(y), state_(state) {}
  int getX() const { return x_; }
  int getY() const { return y_; }
  std::string getState() const { return state_; }

 private:
  int x_;
  int y_;
  std::string state_;
};

3.2.定义发起人类

cpp 复制代码
// Robot类,负责创建和恢复Memento
class Robot {
 public:
  void setPosition(int x, int y) {
    x_ = x;
    y_ = y;
    std::cout << "Position set to: (" << x << ", " << y << ")" << std::endl;
  }

  void setState(const std::string& state) {
    state_ = state;
    std::cout << "State set to: " << state << std::endl;
  }

  Memento saveStateToMemento() { return Memento(x_, y_, state_); }

  void getStateFromMemento(const Memento& memento) {
    x_ = memento.getX();
    y_ = memento.getY();
    state_ = memento.getState();
    std::cout << "State restored to: (" << x_ << ", " << y_ << "), " << state_ << std::endl;
  }

 private:
  int x_;
  int y_;
  std::string state_;
};

3.3.定义管理者类

cpp 复制代码
// Caretaker类,负责保存和恢复Memento
class Caretaker {
 public:
  void addMemento(const Memento& memento) { mementos_.push_back(memento); }

  Memento getMemento(int index) const { return mementos_.at(index); }

 private:
  std::vector<Memento> mementos_;
};

3.4.客户端代码

cpp 复制代码
int main() {
  Robot robot;
  Caretaker caretaker;

  robot.setPosition(0, 0);
  robot.setState("Idle");
  caretaker.addMemento(robot.saveStateToMemento());

  robot.setPosition(10, 20);
  robot.setState("Moving");
  caretaker.addMemento(robot.saveStateToMemento());

  robot.setPosition(30, 40);
  robot.setState("Stopped");

  robot.getStateFromMemento(caretaker.getMemento(0));
  robot.getStateFromMemento(caretaker.getMemento(1));

  return 0;
}
相关推荐
专注VB编程开发20年5 小时前
除了 EasyXLS,加载和显示.xlsx 格式的excel表格,并支持单元格背景色、边框线颜色和粗细等格式化特性
c++·windows·excel·mfc·xlsx
夏天的阳光吖6 小时前
C++蓝桥杯基础篇(四)
开发语言·c++·蓝桥杯
oioihoii7 小时前
C++17 中的 std::to_chars 和 std::from_chars:高效且安全的字符串转换工具
开发语言·c++
张胤尘7 小时前
C/C++ | 每日一练 (2)
c语言·c++·面试
付聪12108 小时前
装饰器模式
设计模式
扣丁梦想家8 小时前
设计模式教程:外观模式(Facade Pattern)
设计模式·外观模式
強云8 小时前
23种设计模式 - 装饰器模式
c++·设计模式·装饰器模式
強云8 小时前
23种设计模式 - 外观模式
设计模式·外观模式
yatingliu20198 小时前
代码随想录算法训练营第六天| 242.有效的字母异位词 、349. 两个数组的交集、202. 快乐数 、1. 两数之和
c++·算法
鄃鳕9 小时前
单例模式【C++设计模式】
c++·单例模式·设计模式