1.Memento 模式的关键是在不破坏封装的前提下,捕获并保存一个类的内部状态,这样就可以利用该保存的状态实施恢复操作。
2.Memento 模式结构图
3.实现
1 #ifndef _MEMENTO_H_ 2 #define _MEMENTO_H_ 3 4 #include <string> 5 using namespace std; 6 class Memento; 7 8 class Originator 9 { 10 public: 11 typedef string State; 12 Originator(); 13 Originator(const State& sdt); 14 ~Originator(); 15 Memento* CreateMemento(); 16 void SetMemento(Memento* men); 17 void RestoreToMemento(Memento* mt); 18 State GetState(); 19 void SetState(const State& sdt); 20 void PrintState(); 21 protected: 22 private: 23 State _sdt; 24 Memento* _mt; 25 }; 26 27 class Memento 28 { 29 public: 30 protected: 31 private: 32 //这是最关键的地方,将Originator为friend类,可以访问内部信息,但是其他类不能访问 33 friend class Originator; 34 typedef string State; 35 Memento(); 36 Memento(const State& sdt); 37 ~Memento(); 38 void SetState(const State& sdt); 39 State GetState(); 40 41 private: 42 State _sdt; 43 }; 44 45 #endif