-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObserver.hpp
100 lines (78 loc) · 1.67 KB
/
Observer.hpp
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
#include <vector>
#include <string>
#include <algorithm>
#include <list>
using namespace std;
static int subCount = 1;
class ISubscriber {
public:
virtual ~ISubscriber() {};
virtual void Update(const string& message_data) = 0;
};
class IPublisher {
public:
virtual ~IPublisher() {};
virtual void Subscribe(ISubscriber* sub) = 0;
virtual void Unsubscribe(ISubscriber* sub) = 0;
virtual void Notify() = 0;
};
class Publisher : public IPublisher {
private:
list<ISubscriber*> subs_;
string message_;
void Notify() {
for (auto sub : subs_) {
sub->Update(message_);
}
}
public:
virtual ~Publisher() {
cout << __LINE__ << ": Publisher destroy" << endl;
}
void CreateMessage(string message = "Empty") {
message_ = message;
Notify();
}
virtual void Subscribe(ISubscriber* sub) {
subs_.push_back(sub);
}
virtual void Unsubscribe(ISubscriber* sub) {
auto subItr = find(subs_.begin(), subs_.end(), sub);
if (subItr != subs_.end()) {
subs_.erase(subItr);
}
}
};
class Subscriber : public ISubscriber {
public:
Subscriber(IPublisher& pub) : pubRef(pub){
pubRef.Subscribe(this);
count_ = subCount++;
cout << "Created Sub: " << count_ << endl;
}
virtual ~Subscriber() {
cout << "Destroy sub: " << count_ << endl;
subCount--;
}
virtual void Update(const string& message_data) {
data_ = message_data;
PrintData();
}
private:
string data_;
IPublisher& pubRef;
void PrintData() {
cout << "Sub: " << count_ << " New data : " << data_ << endl;
}
int count_;
};
class ObserverClient {
public:
ObserverClient() {
Publisher p1;
Subscriber s1(p1);
Subscriber s2(p1);
p1.CreateMessage("Message1");
p1.CreateMessage("Message2");
}
};