标签:
GOF:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
类图:
适用性:
效果:
模板代码:
#include <iostream> #include <string> using namespace std; class Originator; class Memento { public: ~Memento() {} private: friend class Originator; Memento() { m_state = "NULL"; } void setState(string state) { m_state = state; } string getState() { return m_state; } private: string m_state; }; class Originator { public: Memento* createMemento() { return new Memento(); } void setMemento(Memento* memento) { m_state = memento->getState(); } public: void setState(string state) { m_state = state; } string getState() { return m_state; } private: string m_state; }; class CareTaker { public: Memento* getMemento() { return m_pMemento; } void setMemento(Memento* pMemento) { m_pMemento = pMemento; } ~CareTaker() { delete m_pMemento; } private: Memento* m_pMemento; }; int main() { Originator o; o.setState("ON"); cout << "o state : " << o.getState() << endl; CareTaker c; c.setMemento(o.createMemento()); o.setState("OFF"); cout << "o state : " << o.getState() << endl; o.setMemento(c.getMemento()); cout << "o state : " << o.getState() << endl; return 0; }
小结:当你需要某类的历史状态,可以考虑使用备忘录模式。备忘录模式就是维护某类的历史状态,利用CareTaker封装备份与恢复的细颗粒操作。
标签:
原文地址:http://www.cnblogs.com/programmer-kaima/p/4526258.html