Memento 模式的关键就是要在不破坏封装行的前提下,捕获并保存一个类的内部状态,这样就可以利用该保存的状态实施恢复操作。
1 /Originator.h// 2 #pragma once 3 #include <string> 4 using namespace std; 5 typedef string State ; 6 7 class Memento ; 8 class Originator 9 { 10 public: 11 Originator(); 12 Originator(const State& std); 13 ~Originator(); 14 Memento* GreatMemento(); 15 void SetMemento(); 16 void RestoreToMemento(); 17 State GetState(); 18 void SetState(const State& sdt); 19 void PrintState(); 20 21 protected: 22 private: 23 State _sdt ; 24 Memento* _mt; 25 };
/Memento.h// #pragma once #include <string> using namespace std; typedef string State ; class Memento { public: protected: private: friend class Originator ; Memento(); Memento(const State& sdt); ~Memento(); void SetState(const State& sdt); State GetState(); State _sdt ; };
1 Originator.cpp/ 2 #include "Originator.h" 3 #include "Memento.h" 4 #include <iostream> 5 using namespace std; 6 Originator::Originator(const State& std) 7 { 8 _sdt = std ; 9 _mt = 0; 10 } 11 Originator::Originator() 12 { 13 _sdt = "" ; 14 _mt = 0; 15 } 16 void Originator::SetMemento() 17 { 18 if (_mt == 0) 19 { 20 this->_mt = GreatMemento(); 21 } 22 else 23 { 24 _mt->SetState(_sdt); 25 } 26 27 } 28 Memento* Originator::GreatMemento() 29 { 30 return new Memento(_sdt); 31 } 32 void Originator::RestoreToMemento() 33 { 34 if (this->_mt != 0) 35 { 36 _sdt = _mt->GetState(); 37 } 38 39 } 40 void Originator::SetState(const State& sdt) 41 { 42 _sdt = sdt ; 43 } 44 45 State Originator::GetState() 46 { 47 return _sdt; 48 } 49 50 void Originator::PrintState() 51 { 52 cout<<this->_sdt<<"....."<<endl; 53 } 54 Originator::~Originator() 55 { 56 delete _mt; 57 }
1 ///Memento.cpp/ 2 #include "Memento.h" 3 #include <string> 4 using namespace std; 5 6 typedef string State ; 7 8 Memento::Memento(const State& sdt) 9 { 10 _sdt = sdt ; 11 } 12 Memento::Memento() 13 { 14 15 } 16 void Memento::SetState(const State& sdt) 17 { 18 _sdt = sdt ; 19 } 20 21 State Memento::GetState() 22 { 23 return _sdt ; 24 } 25 Memento::~Memento() 26 { 27 28 }
1 ///main.cpp/// 2 #include "Memento.h" 3 #include "Originator.h" 4 #include <string> 5 #include <iostream> 6 using namespace std; 7 8 typedef string State ; 9 10 int main() 11 { 12 Originator* O = new Originator(); 13 O->SetState("备忘前状态 Old"); 14 O->PrintState(); 15 16 O->SetMemento();//备忘 17 18 O->SetState("备忘后状态 New"); 19 O->PrintState(); 20 21 O->RestoreToMemento();//恢复 22 23 O->PrintState(); 24 25 getchar(); 26 return 0 ; 27 }