Skip to content

Commit a54ae84

Browse files
committed
Mediator 中介者
1 parent 133300b commit a54ae84

2 files changed

Lines changed: 95 additions & 1 deletion

File tree

src/15MediatorPattern.h

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
//Mediator(中介者模式-对象行为型)
2+
//用一个中介对象来封装一系列的对象交互。
3+
//中介者使各对象不需要显式地相互引用,从而使其耦合松散,
4+
//而且可以独立地改变它们之间的交互。
5+
#include <iostream>
6+
7+
//不知道为什么书上用Colleague(同事)一词来表示协作类
8+
class Colleague;
9+
10+
//中介者接口
11+
class Mediator
12+
{
13+
public:
14+
virtual ~Mediator() {}
15+
virtual void notify(Colleague* sender, int type) = 0;
16+
};
17+
18+
//"同事"类接口
19+
class Colleague
20+
{
21+
public:
22+
virtual ~Colleague() {}
23+
void setMediator(Mediator* ptr) {
24+
mediator = ptr;
25+
}
26+
void notify(int type) {
27+
std::cout << "Colleague notify:" << type << std::endl;
28+
if (!mediator) {
29+
return;
30+
}
31+
mediator->notify(this, type);
32+
}
33+
private:
34+
Mediator* mediator{ nullptr };
35+
};
36+
37+
//具体的同事类1
38+
class ConcreteColleague1 : public Colleague
39+
{
40+
public:
41+
void update() {
42+
std::cout << "ConcreteColleague1 update" << std::endl;
43+
}
44+
};
45+
46+
//具体的同事类2
47+
class ConcreteColleague2 : public Colleague
48+
{
49+
public:
50+
void update() {
51+
std::cout << "ConcreteColleague2 update" << std::endl;
52+
}
53+
};
54+
55+
//具体的中介者类
56+
class ConcreteMediator : public Mediator
57+
{
58+
public:
59+
ConcreteMediator(ConcreteColleague1* c1, ConcreteColleague2* c2)
60+
: colleague1(c1), colleague2(c2) {
61+
c1->setMediator(this);
62+
c2->setMediator(this);
63+
}
64+
~ConcreteMediator() {}
65+
//具体的交互逻辑
66+
void notify(Colleague* sender, int type) override {
67+
std::cout << "ConcreteMediator notify:" << type << std::endl;
68+
if (type == 1 && sender == colleague1) {
69+
colleague2->update();
70+
}
71+
else {
72+
colleague1->update();
73+
colleague2->update();
74+
}
75+
}
76+
private:
77+
ConcreteColleague1* colleague1;
78+
ConcreteColleague2* colleague2;
79+
};
80+
81+
//测试
82+
void testMediatorPattern()
83+
{
84+
ConcreteColleague1 c1;
85+
ConcreteColleague2 c2;
86+
ConcreteMediator mediator(&c1, &c2);
87+
//通过中介者去处理关联逻辑
88+
std::cout << "c1 notify" << std::endl;
89+
c1.notify(1);
90+
std::cout << "c2 notify" << std::endl;
91+
c2.notify(1);
92+
}

src/main.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#include "12FacadePattern.h"
1414
#include "13ProxyPattern.h"
1515
#include "14AdapterPattern.h"
16+
#include "15MediatorPattern.h"
1617

1718
int main()
1819
{
@@ -29,7 +30,8 @@ int main()
2930
//testFlayweightPattern();
3031
//testFacadePattern();
3132
//testProxyPattern();
32-
testAdapterPattern();
33+
//testAdapterPattern();
34+
testMediatorPattern();
3335

3436
getchar();
3537
return 0;

0 commit comments

Comments
 (0)