来自于《大话设计模式》
终结者模式(Mediator):
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互作用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
行为型
UML 类图:
代码实现 C++:
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class Country;
6
7 class UnitedNations
8 {
9 public:
10 virtual void Declare(const string& message, Country* colleague) = 0;
11 virtual void setColleague1(Country* c1) = 0;
12 virtual void setColleague2(Country* c2) = 0;
13 };
14
15 class Country
16 {
17 protected:
18 UnitedNations* mediator;
19 public:
20 Country(UnitedNations* un) : mediator(un) {}
21 virtual void Declare(const string& message) = 0;
22 virtual void GetMessage(const string& message) = 0;
23 };
24
25 class USA : public Country
26 {
27 public:
28 USA(UnitedNations* un) : Country(un) {}
29 void Declare(const string& message)
30 {
31 mediator->Declare(message, this);
32 }
33 void GetMessage(const string& message)
34 {
35 cout << "美国获得对方信息:" << message << endl;
36 }
37 };
38
39 class Iraq : public Country
40 {
41 public:
42 Iraq(UnitedNations* un) : Country(un) {}
43 void Declare(const string& message)
44 {
45 mediator->Declare(message, this);
46 }
47 void GetMessage(const string& message)
48 {
49 cout << "伊拉克获得对方信息:" << message << endl;
50 }
51 };
52
53 class UnitedNationsSecurityCouncil : public UnitedNations
54 {
55 private:
56 Country* colleague1;
57 Country* colleague2;
58 public:
59 void setColleague1(Country* u)
60 {
61 colleague1 = u;
62 }
63 void setColleague2(Country* i)
64 {
65 colleague2 = i;
66 }
67 virtual void Declare(const string& message, Country* colleague)
68 {
69 if (colleague == colleague1)
70 {
71 colleague2->GetMessage(message);
72 }
73 else
74 {
75 colleague1->GetMessage(message);
76 }
77 }
78 };
79
80 int main()
81 {
82 UnitedNationsSecurityCouncil* UNSC = new UnitedNationsSecurityCouncil;
83 USA* c1 = new USA(UNSC);
84 Iraq* c2 = new Iraq(UNSC);
85
86 UNSC->setColleague1(c1);
87 UNSC->setColleague2(c2);
88
89 c1->Declare("不准研制核武器,否则要发动战争!");
90 c2->Declare("我们没有核武器,也不怕侵略!");
91
92 delete c2;
93 delete c1;
94 delete UNSC;
95
96 return 0;
97 }
posted on 2011-04-30 12:02
unixfy 阅读(502)
评论(0) 编辑 收藏 引用