-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathobserver.cc
More file actions
120 lines (105 loc) · 2.15 KB
/
observer.cc
File metadata and controls
120 lines (105 loc) · 2.15 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct INotify
{
virtual void Notify(string info) = 0;
operator INotify*()
{
return this;
}
};
class Doordarshan : public INotify
{
public:
virtual void Notify(string info)
{
cout<<"Doordarshan received :"<<info<<endl;
}
};
class NDTV : public INotify
{
public:
virtual void Notify(string info)
{
cout<<"NDTV received :"<<info<<endl;
}
};
class TimesNow : public INotify
{
public:
virtual void Notify(string info)
{
cout<<"TIMESNOW received :"<<info<<endl;
}
};
class Publisher
{
protected:
string name;
//move below stuff to different class and have its reference and just invoke the BroadCast on it
//violates SRP
map<string, INotify*> subscribers;
void BroadCast(string info)
{
auto it = subscribers.begin();
while(it != subscribers.end())
{
it->second->Notify(name+":"+info);
it++;
}
}
public:
Publisher(string name) : name(name){}
void Subscribe(string key, INotify *client)
{
subscribers[key] = client;
}
};
class Election : public Publisher
{
public:
Election() : Publisher("Election"){}
void ElectionResult(string info)
{
BroadCast(info);
}
};
class Entertainment : public Publisher
{
public:
Entertainment() : Publisher("Entertainment"){}
void EntertainmentNews(string info)
{
BroadCast(info);
}
};
class Sports : public Publisher
{
public:
Sports() : Publisher("Sports"){}
void SportsNews(string info)
{
BroadCast(info);
}
};
int main()
{
Doordarshan dd;
NDTV ndtv;
TimesNow tn;
Election elec;
Entertainment ent;
Sports sport;
elec.Subscribe("dd", dd);
elec.Subscribe("ndtv",ndtv);
elec.Subscribe("tn", tn);
ent.Subscribe("ndtv", ndtv);
ent.Subscribe("tn", tn);
sport.Subscribe("tn", tn);
elec.ElectionResult("NDA Wins with 300+ seats");
ent.EntertainmentNews("RaGa fools people with promise of 72k per year");
sport.SportsNews("RCB loosing each and every match");
return 0;
}