设计模式探秘-11-中介者模式

中介者模式的学习与实践

中介者模式

中介者模式:用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散可以独立地改变它们之间的交互。

类图

优点

减少类间的依赖,将原有的一对多的依赖变成一对一的依赖。降低类间的耦合。

缺点

中介者会膨胀的很大,而且逻辑复杂,原先对象直接的依赖关系转换为中介者和同事类的依赖关系,同事类越多,中介者的逻辑就越复杂。

使用场景

类图中出现了蜘蛛网状结构,使用中介者模式将蜘蛛网梳理为星形结构,使混乱的关系变得清晰简单。

注意事项

扩展

实践

简单实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
//中介者模式
class Mediator;
class Colleage
{
public:
~Colleage() {}
virtual void Action() = 0;
virtual void SetState(const string &sdt) = 0;
virtual string GetState() = 0;
protected:
Colleage() {}
Colleage(Mediator *mdt)
{
m_pMdt = mdt;
}
Mediator *m_pMdt;
};

class Mediator
{
public:
virtual ~Mediator() {};
virtual void ActionA() = 0;
virtual void ActionB() = 0;
protected:
Mediator() {};
};

class ConcreteMediator : public Mediator
{
public:
ConcreteMediator() {}
ConcreteMediator(Colleage *clgA, Colleage *clgB)
{
m_pClgA = clgA;
m_pClgB = clgB;
}
~ConcreteMediator() {}
void SetConcreteColleageA(Colleage *clgA)
{
m_pClgA = clgA;
}
void SetConcreteColleageB(Colleage *clgB)
{
m_pClgB = clgB;
}
Colleage *GetConcreteColleageA()
{
return m_pClgA;
}
Colleage *GetConcreteColleageB()
{
return m_pClgB;
}
void IntroColleage(Colleage *clgA, Colleage *clgB)
{
m_pClgA = clgA;
m_pClgB = clgB;
}
void ActionA()
{
cout<<__FUNCTION__<<" A "<<m_pClgA->GetState()<<endl;
}
void ActionB()
{
cout<<__FUNCTION__<<" B "<<m_pClgB->GetState()<<endl;
}
private:
Colleage * m_pClgA;
Colleage * m_pClgB;
};


class ConcreteColleageA : public Colleage
{
public:
ConcreteColleageA() {}
ConcreteColleageA(Mediator *mdt) : Colleage(mdt)
{
;
}
~ConcreteColleageA() {}
void Action()
{
m_pMdt->ActionB();
cout<<"state of ConcreteColleageA:"<<GetState()<<endl;
}
void SetState(const string& sdt)
{
m_sSdt = sdt;
}
string GetState()
{
return m_sSdt;
}
private:
string m_sSdt;
};

class ConcreteColleageB : public Colleage
{
public:
ConcreteColleageB() {}
ConcreteColleageB(Mediator *mdt) : Colleage(mdt)
{
;
}
~ConcreteColleageB() {}
void Action()
{
m_pMdt->ActionA();
cout<<"state of ConcreteColleageB:"<<GetState()<<endl;
}
void SetState(const string& sdt)
{
m_sSdt = sdt;
}
string GetState()
{
return m_sSdt;
}
private:
string m_sSdt;
};

int main()
{
ConcreteMediator *m = new ConcreteMediator();

ConcreteColleageA *ca = new ConcreteColleageA(m);
ConcreteColleageB *cb = new ConcreteColleageB(m);

m->IntroColleage(ca, cb);
m->ActionA();

ca->SetState("a");
cb->SetState("b");
cout<<ca->GetState()<<endl;
cout<<cb->GetState()<<endl;
ca->Action();
cb->Action();

return 0;
}

参考资料

  1. 设计模式之禅
  2. GoF+23种设计模式解析