-
Notifications
You must be signed in to change notification settings - Fork 55
/
mediator.cpp
89 lines (71 loc) · 2.05 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
#include <iostream>
#include <list>
#include <memory>
#include <string_view>
#include <utility>
namespace jc {
class Colleague;
class Mediator {
public:
virtual void Notify(const std::shared_ptr<Colleague>&, std::string_view) = 0;
virtual ~Mediator() = default;
};
class Colleague {
public:
explicit Colleague(const std::shared_ptr<Mediator>& p) : mediator_(p) {}
virtual void Send(std::string_view) = 0;
virtual void Receive(std::string_view) const = 0;
virtual ~Colleague() = default;
protected:
std::weak_ptr<Mediator> mediator_;
};
class ColleagueA : public Colleague,
public std::enable_shared_from_this<ColleagueA> {
public:
using Colleague::Colleague;
void Send(std::string_view s) override {
mediator_.lock()->Notify(shared_from_this(), s);
}
void Receive(std::string_view s) const override {
std::cout << "A receive: " << s << '\n';
}
};
class ColleagueB : public Colleague,
public std::enable_shared_from_this<ColleagueB> {
public:
using Colleague::Colleague;
void Send(std::string_view s) override {
mediator_.lock()->Notify(shared_from_this(), s);
}
void Receive(std::string_view s) const override {
std::cout << "B receive: " << s << '\n';
}
};
class ConcreteMediator : public Mediator {
public:
void Append(const std::shared_ptr<Colleague>& c) {
colleagues_.emplace_back(c);
}
void Notify(const std::shared_ptr<Colleague>& c,
std::string_view s) override {
for (auto&& x : colleagues_) {
if (const auto p = x.lock()) {
if (p != c) {
p->Receive(s);
}
}
}
}
private:
std::list<std::weak_ptr<Colleague>> colleagues_;
};
} // namespace jc
int main() {
auto mediator = std::make_shared<jc::ConcreteMediator>();
auto colleagueA = std::make_shared<jc::ColleagueA>(mediator);
auto colleagueB = std::make_shared<jc::ColleagueB>(mediator);
mediator->Append(colleagueA);
mediator->Append(colleagueB);
colleagueA->Send("hello"); // B receive: hello
colleagueB->Send("world"); // A receive: world
}