-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmediator.cpp
More file actions
84 lines (71 loc) · 2.3 KB
/
mediator.cpp
File metadata and controls
84 lines (71 loc) · 2.3 KB
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
// mediator design pattern
#include <iostream>
#include <set>
#include <string>
using string = std::string;
class Entity {
public:
virtual void sendMessage(const string& msg) = 0;
virtual void receiveMessage(const string& msg) = 0;
};
class Mediator {
public:
virtual void notify(string msg, Entity* sender) = 0; // has to have sender, regardless of scenario - don't want loopback
};
class AirTrafficControl : public Mediator { // more like a radio tower
public:
void connect(Entity* entity) {
entities.insert(entity);
}
void disconnect(Entity* entity) {
entities.erase(entity);
}
void notify(string msg, Entity* sender) override {
for (auto& entity : entities) {
if (entity != sender) {
entity->receiveMessage(msg);
}
}
}
private:
std::set<Entity*> entities; // unordered!!! - faster access under BST
};
class Aircraft : public Entity {
string name;
AirTrafficControl* atc;
public:
Aircraft(const std::string& name, AirTrafficControl* atc) : name(name), atc(atc) {
atc->connect(this);
}
void sendMessage(const std::string& message) override {
std::cout << name << " (Plane) sends message: " << message << std::endl;
atc->notify(name + ": " + message, this);
}
void receiveMessage(const std::string& message) override {
std::cout << name << " (Plane) received message: " << message << std::endl;
}
};
class GroundCrew : public Entity {
string name;
AirTrafficControl* atc;
public:
GroundCrew(const std::string& name, AirTrafficControl* atc) : name(name), atc(atc) {
atc->connect(this);
}
void sendMessage(const std::string& message) override {
std::cout << name << " (GroundCrew) sends message: " << message << std::endl;
atc->notify(name + ": " + message, this);
}
void receiveMessage(const std::string& message) override {
std::cout << name << " (GroundCrew) received message: " << message << std::endl;
}
};
int main() {
AirTrafficControl atc;
Aircraft flight1("AA 123", &atc);
Aircraft flight2("UA 678", &atc);
GroundCrew firetruck("Fire Crew 1", &atc);
firetruck.sendMessage("In position to salute UA 678");
flight1.sendMessage("Requesting permission to land");
return 0;
}