c++ 行为型模式_备忘录(Memento)
1) 意图
在不破坏封装性的前提下,捕获一个对象的内部状态,并在对象之外保存这个状态。这样可以将对象恢复到原先保存的状态
2) 结构
其中
- Memento (备忘录)存储Originator内部状态
- Originator(原发器)创建一个Memento,用于记录当前时刻它的内部状态
- Caretaker (管理者)负责保存好备忘录,但不能操作或检查备忘录的内容
3) 适用性
- 必须保存一个对象在某一个时刻的状态,以便需要时恢复此前状态
- 如果提供一个接口让其他对象得到这些状态,将会暴露对象的实现细节并破坏对象的封装性
4) 举例
1 #include <iostream> 2 typedef std::string STATE; 3 class Originator; 4 class Memento 5 { 6 public: 7 virtual ~Memento() {} 8 private: 9 friend Originator; 10 Memento(STATE& state):m_state(state){} 11 void setState(STATE& state) 12 { 13 m_state = state; 14 } 15 STATE getState() 16 { 17 return m_state; 18 } 19 STATE m_state; 20 }; 21 class Originator 22 { 23 public: 24 Originator(STATE& state) :m_state(state) {} 25 virtual ~Originator() {} 26 void setState(std::string& state) 27 { 28 m_state = state; 29 } 30 void setMemento(Memento* pMememnto) 31 { 32 m_state = pMememnto->getState(); 33 } 34 Memento* createMemento() 35 { 36 return new Memento(m_state); 37 } 38 void print() 39 { 40 std::cout << " Memento : " << m_state.c_str() << std::endl; 41 } 42 private: 43 STATE m_state; 44 }; 45 class Caretaker 46 { 47 public: 48 Caretaker():m_pMemnto(NULL) {} 49 virtual ~Caretaker() {} 50 void setMemento(Memento* p_Memento) 51 { 52 m_pMemnto = p_Memento; 53 } 54 Memento* getCountMemento() 55 { 56 return m_pMemnto; 57 } 58 private: 59 Memento* m_pMemnto; 60 }; 61 62 int main() 63 { 64 Caretaker* pCaretaker = new Caretaker(); 65 66 Originator* pOriginator = new Originator(std::string("hello")); 67 pOriginator->print();// 显示当前状态 68 Memento* pMemnto = pOriginator->createMemento(); 69 pCaretaker->setMemento(pMemnto);//保存备忘录 70 pOriginator->setState(std::string("world"));//修改状态 71 pOriginator->print();// 显示修改后的状态 72 73 //通过备忘录恢复初始状态 74 pOriginator->setMemento(pCaretaker->getCountMemento()); 75 pOriginator->print(); 76 77 delete pCaretaker; 78 delete pOriginator; 79 delete pMemnto; 80 system("pause"); 81 }