备忘录模式
#include <iostream> #include <memory> #include <vector> class Momento { public: Momento(std::string state) { this->state_ = state; } std::string state() { return state_; } private: std::string state_ = ""; }; class Originator { public: std::shared_ptr<Momento> save() { return std::make_shared<Momento>(state_); } void setState(std::string state) { this->state_ = state; } void restore(std::shared_ptr<Momento> m) { this->state_ = m->state(); } void show() { std::cout << "In Originator show(). The state is " << state_ << std::endl; } private: std::string state_ = ""; }; class Caretaker { public: Caretaker(std::shared_ptr<Originator> o) { this->o = o; } void backUp() { std::shared_ptr<Momento> m = o->save(); mv.push_back(m); } void undo() { if(!mv.empty()) { mv.pop_back(); if(!mv.empty()) { o->restore(mv.back()); } } } private: std::shared_ptr<Originator> o = nullptr; std::vector<std::shared_ptr<Momento>> mv; }; int main(int argc, char *argv[]) { std::shared_ptr<Originator> o = std::make_shared<Originator>(); std::shared_ptr<Caretaker> c = std::make_shared<Caretaker>(o); o->setState("1"); o->show(); c->backUp(); o->setState("2"); c->backUp(); o->show(); c->undo(); o->show(); return 1; }