-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.cpp
67 lines (53 loc) · 1.47 KB
/
observer.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
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class ObserverInterface {
public:
virtual void update(string msg) = 0;
};
class SubjectInterface {
public:
virtual void subscribe(ObserverInterface *observer) = 0;
virtual void unsubscribe(ObserverInterface *observer) = 0;
virtual void notifyAll(string msg) = 0;
std::vector<ObserverInterface*> m_observers;
};
class MySubject : public SubjectInterface {
public:
void subscribe(ObserverInterface *observer) {
m_observers.push_back(observer);
}
void unsubscribe(ObserverInterface *observer) {
int i;
for(i=0; i < m_observers.size(); i++) {
if (observer == m_observers[i])
break;
}
m_observers.erase(m_observers.begin() + i);
}
void notifyAll(string msg) {
std::for_each(m_observers.begin(), m_observers.end(), [msg](ObserverInterface *observer) {
observer->update(msg);
});
}
};
class Myobserver : public ObserverInterface {
string m_name;
public:
Myobserver(string name) : m_name(name) {}
void update(string msg) { cout << "message recieved " << msg << " by observer " << m_name << endl;}
};
int main()
{
Myobserver o1("mj1");
Myobserver o2("mj2");
Myobserver o3("mj3");
MySubject s;
s.subscribe(&o1);
s.subscribe(&o2);
s.subscribe(&o3);
s.notifyAll("hey everyone");
return 0;
}