TAG:
作用:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
UML结构图:
解析: Memento模式中封装的是需要保存的状态,当需要恢复的时候才取出来进行恢复。原理很简单,实现的时候需要注意一个地方:窄接口和宽接口。所谓的宽接口就是一般意义上的接口,把对外的接口作为public成员;而窄接口反之,把接口作为private成员,而把需要访问这些接口函数的类作为这个类的友元类,也就是说接口只暴露给了对这些接口感兴趣的类,而不是暴露在外部。下面的实现就是窄实现的方法来实现的。
代码实现: Memento.h 1 #ifndef MEMENTO_H
2 #define MEMENTO_H 3 4 #include <string> 5 6 typedef std::string State; 7 8 class Memento; 9 10 class Originator 11 { 12 public: 13 Originator(const State& rState); 14 Originator(); 15 ~Originator(); 16 17 Memento* CreateMemento(); 18 void SetMemento(Memento* pMemento); 19 State GetState(); 20 void SetState(const State& rState); 21 void RestoreState(Memento* pMemento); 22 void PrintState(); 23 24 private: 25 State m_State; 26 }; 27 28 // 把Memento的接口函数都设置为私有的,而Originator是它的友元, 29 // 这样保证了只有Originator可以对其访问 30 class Memento 31 { 32 private: 33 friend class Originator; 34 Memento(const State& rState); 35 void SetState(const State& rState); 36 State GetState(); 37 38 State m_State; 39 }; 40 41 #endif Memento.cpp 1
2 #include "Memento.h" 3 #include <iostream> 4 5 Originator::Originator() 6 { 7 8 } 9 10 Originator::Originator(const State& rState) 11 : m_State(rState) 12 { 13 14 } 15 16 Originator::~Originator() 17 { 18 19 } 20 21 State Originator::GetState() 22 { 23 return m_State; 24 } 25 26 void Originator::SetState(const State& rState) 27 { 28 m_State = rState; 29 } 30 31 Memento* Originator::CreateMemento() 32 { 33 return new Memento(m_State); 34 } 35 36 void Originator::RestoreState(Memento* pMemento) 37 { 38 if (NULL != pMemento) 39 { 40 m_State = pMemento->GetState(); 41 } 42 } 43 44 void Originator::PrintState() 45 { 46 std::cout << "State = " << m_State << std::endl; 47 } 48 49 Memento::Memento(const State& rState) 50 : m_State(rState) 51 { 52 53 } 54 55 State Memento::GetState() 56 { 57 return m_State; 58 } 59 60 void Memento::SetState(const State& rState) 61 { 62 m_State = rState; 63 } Main.cpp 1
2 #include "Memento.h" 3 4 int main() 5 { 6 // 创建一个原发器 7 Originator* pOriginator = new Originator("old state"); 8 pOriginator->PrintState(); 9 10 // 创建一个备忘录存放这个原发器的状态 11 Memento *pMemento = pOriginator->CreateMemento(); 12 13 // 更改原发器的状态 14 pOriginator->SetState("new state"); 15 pOriginator->PrintState(); 16 17 // 通过备忘录把原发器的状态还原到之前的状态 18 pOriginator->RestoreState(pMemento); 19 pOriginator->PrintState(); 20 21 delete pOriginator; 22 delete pMemento; 23 24 return 0; 25 } |