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

发布于:2025-02-11 ⋅ 阅读:(38) ⋅ 点赞:(0)

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

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

1.问题分析

在开发中,有时需要保存对象的状态,以便在需要时恢复到之前的状态。这种需求在撤销/重做操作、游戏存档、编辑器状态恢复等场景中尤为常见。
备忘录模式通过将对象的状态封装在一个独立的备忘录对象中,实现了状态的保存和恢复,同时保持了对象的封装性。

2.实现步骤

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

3.代码示例

3.1.定义备忘录类

// 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.定义发起人类

// 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.定义管理者类

// 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.客户端代码

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;
}

网站公告

今日签到

点亮在社区的每一天
去签到