1.Memento 模式的关键是在不破坏封装的前提下,捕获并保存一个类的内部状态,这样就可以利用该保存的状态实施恢复操作。

2.Memento 模式结构图

Memento Pattern

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
Memento.h

相关文章:

  • 2022-12-23
  • 2021-12-31
  • 2021-12-31
  • 2021-09-15
  • 2021-06-23
  • 2022-02-16
猜你喜欢
  • 2022-03-03
  • 2021-06-28
  • 2022-03-06
  • 2021-12-27
  • 2021-06-06
相关资源
相似解决方案