网站备案帐号是什么情况,企查查怎么精准找客户,开发公司档案管理制度,阿里巴巴的网站二维码怎么做链接#xff1a;C 设计模式 链接#xff1a;C 设计模式 - 状态模式
备忘录模式#xff08;Memento Pattern#xff09;是一种行为设计模式#xff0c;它允许在不破坏封装性的前提下捕获和恢复对象的内部状态。这个模式在需要保存和恢复对象状态的场景中非常有用#xff…链接C 设计模式 链接C 设计模式 - 状态模式
备忘录模式Memento Pattern是一种行为设计模式它允许在不破坏封装性的前提下捕获和恢复对象的内部状态。这个模式在需要保存和恢复对象状态的场景中非常有用例如实现撤销操作。
1.问题分析
在开发中有时需要保存对象的状态以便在需要时恢复到之前的状态。这种需求在撤销/重做操作、游戏存档、编辑器状态恢复等场景中尤为常见。 备忘录模式通过将对象的状态封装在一个独立的备忘录对象中实现了状态的保存和恢复同时保持了对象的封装性。
2.实现步骤
定义备忘录类存储对象的内部状态定义发起人类负责创建和恢复备忘录。定义管理者类负责保存和管理备忘录对象。客户端代码实现保存状态到备忘录和从备忘录恢复状态。
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::vectorMemento 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;
}