
1 #include <iostream>
2 #include <string>
3 #include <vector>
4
5 using namespace std;
6
7 class STMemento
8 {
9 private:
10 int iVitality;
11 public:
12 STMemento(){}
13 STMemento(int iVitality)
14 {
15 this->iVitality = iVitality;
16 }
17
18 int GetVitality() const
19 {
20 return this->iVitality;
21 }
22 };
23
24 class STOriginator
25 {
26 private:
27 int iVitality;
28 string name;
29 public:
30 STOriginator(string strName, int iVit): iVitality(iVit), name(strName)
31 {
32
33 }
34
35 STMemento* SaveState()
36 {
37 return new STMemento(iVitality);
38 }
39
40 void RecoverState(const STMemento* stMemento)
41 {
42 this->iVitality = stMemento->GetVitality();
43 }
44
45 void SetVitality(int iVit)
46 {
47 this->iVitality = iVit;
48 }
49
50 void Show()
51 {
52 cout<< "Name: "<< name<< endl;
53 cout<< "Live: "<< iVitality<< endl;
54 }
55 };
56
57 class STCareTaker
58 {
59 private:
60 vector<STMemento*> vecStMemento;
61
62 public:
63 void AddMemento(STMemento* stMemento)
64 {
65 vecStMemento.push_back(stMemento);
66 }
67
68 STMemento* GetMemento(int Iindex)
69 {
70 if (Iindex >= vecStMemento.size())
71 return NULL;
72 else
73 return vecStMemento[Iindex];
74 }
75 };
76
77 int main(int argc, char* argv[])
78 {
79 STOriginator* pstOriginator = new STOriginator("xxx", 100);
80 cout<< "原始状态: "<< endl;
81 pstOriginator->Show();
82
83 STCareTaker* pstCareTaker = new STCareTaker();
84 pstCareTaker->AddMemento(pstOriginator->SaveState());
85
86 pstOriginator->SetVitality(50);
87 cout<< "战斗后状态: "<< endl;
88 pstOriginator->Show();
89
90 pstOriginator->RecoverState(pstCareTaker->GetMemento(0));
91 cout<< "归档后状态: "<< endl;
92 pstOriginator->Show();
93
94 return 0;
95 }
96 /////////////////////////////
97 [root@ ~/learn_code/design_pattern/15_memento]$ ./memento
98 原始状态:
99 Name: xxx
100 Live: 100
101
102 战斗后状态:
103 Name: xxx
104 Live: 50
105
106 归档后状态:
107 Name: xxx
108 Live: 100