备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
UML 类图:
代码实现 C++:
1 #include <iostream>
2 using namespace std;
3
4 class RoleStateMemento
5 {
6 public:
7 int vit;
8 int atk;
9 int def;
10 public:
11 RoleStateMemento(int v = 0, int a = 0, int d = 0) : vit(v), atk(a), def(d) {}
12 };
13
14 class Roles
15 {
16 private:
17 int vit;
18 int atk;
19 int def;
20 public:
21 Roles(int v = 100, int a = 100, int d = 100) : vit(v), atk(a), def(d) {}
22 void getInitState()
23 {
24 vit = 100;
25 atk = 100;
26 def = 100;
27 }
28 void fight()
29 {
30 vit = 0;
31 atk = 0;
32 def = 0;
33 }
34 void displayState()
35 {
36 cout << "体力:" << vit << endl;
37 cout << "攻击力:" << atk << endl;
38 cout << "防御力:" << def << endl;
39 }
40 RoleStateMemento SaveState()
41 {
42 return RoleStateMemento(vit, atk, def);
43 }
44 void RecoveryState(const RoleStateMemento& memento)
45 {
46 vit = memento.vit;
47 atk = memento.atk;
48 def = memento.def;
49 }
50 };
51
52 class RoleStateCaretaker
53 {
54 private:
55 public:
56 RoleStateMemento memento;
57 };
58
59 int main()
60 {
61 Roles* r = new Roles;
62 r->getInitState();
63 r->displayState();
64
65 RoleStateCaretaker* stateAdmin = new RoleStateCaretaker;
66 stateAdmin->memento = r->SaveState();
67
68 r->fight();
69 r->displayState();
70
71 r->RecoveryState(stateAdmin->memento);
72 r->displayState();
73
74 return 0;
75 }
posted on 2011-04-29 08:43
unixfy 阅读(138)
评论(0) 编辑 收藏 引用