-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediator.cpp
90 lines (81 loc) · 1.9 KB
/
mediator.cpp
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
//用一个中介对象来封装一系列的对象。
//中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
//https://blog.csdn.net/naibozhuan3744/article/details/108927422
#include <iostream>
#include <vector>
class Colleague;
class IMediator
{
protected:
std::vector<Colleague*> colleagues;
public:
IMediator() :colleagues(0) {}
virtual ~IMediator() {}
virtual void add(Colleague* colleague) = 0;
virtual void send(Colleague* colleague) = 0;
};
class Colleague
{
protected:
IMediator* mediator;
public:
Colleague(IMediator* mediator) :mediator(mediator) {}
virtual void notify() = 0;
virtual void send() = 0;
};
class ConcreteColleague1 : public Colleague
{
public:
ConcreteColleague1(IMediator* mediator) : Colleague(mediator) {}
virtual void notify()
{
std::cout << "This is ConcreteColleague1" << std::endl;
}
virtual void send()
{
mediator->send(this);
}
};
class ConcreteColleague2 : public Colleague
{
public:
ConcreteColleague2(IMediator* mediator) : Colleague(mediator) {}
virtual void notify()
{
std::cout << "This is ConcreteColleague2" << std::endl;
}
virtual void send()
{
mediator->send(this);
}
};
class ConcreteMediator : public IMediator
{
public:
void add(Colleague* colleague) override
{
colleagues.emplace_back(colleague);
}
void send(Colleague* colleague) override
{
for (const auto& it : colleagues)
{
if (it == colleague)
{
it->notify();
break;
}
}
}
};
//int main()
//{
// IMediator* mediator = new ConcreteMediator();
// Colleague* colleague1 = new ConcreteColleague1(mediator);
// Colleague* colleague2 = new ConcreteColleague2(mediator);
// mediator->add(colleague1); // 中介者把同事加入同事集合
// mediator->add(colleague2);
//
// colleague1->send(); // 租客在中介者发布租房信息
// colleague2->send(); // 房东也在中介者发布出租房信息
//}