备忘录模式

【1】什么是备忘录模式?

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。

这样就可以将该对象恢复到原先保存的状态。

【2】备忘录模式的代码示例:

代码示例如下:

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 class Memo
 7 {
 8 public:
 9     string state;
10     Memo(string state)
11     {
12         this->state = state;
13     }
14 };
15 
16 class Originator
17 {
18 public:
19     string state;
20     void setMemo(Memo *memo)
21     {
22         state = memo->state;
23     }
24     Memo *createMemo()
25     {
26         return new Memo(state);
27     }
28     void show()
29     {
30         cout << state << endl;
31     }
32 };    
33 
34 class Caretaker
35 {
36 public:
37     vector<Memo *> memo;
38 public:
39     void save(Memo *memo)
40     {
41         (this->memo).push_back(memo);
42     }
43     Memo *getState(int i)
44     {
45         return memo[i];
46     }
47 };
48  
49 int main()
50 {
51     Originator *og = new Originator();
52     Caretaker *ct = new Caretaker(); 
53 
54     og->state = "on";
55     og->show();    
56     ct->save(og->createMemo());
57 
58     og->state = "off";
59     og->show();
60     ct->save(og->createMemo());
61 
62     og->state = "middle";
63     og->show();
64     ct->save(og->createMemo());
65 
66     og->setMemo( ct->getState(1) );
67     og->show();
68 
69     return 0;
70 }
71 //Result:
72 /*
73 on
74 off
75 middle
76 off
77 */
View Code

 

Good  Good  Study, Day  Day  Up.

顺序  选择   循环   总结

posted @ 2014-08-30 21:14  kaizenly  阅读(218)  评论(0编辑  收藏  举报
打赏