-
Notifications
You must be signed in to change notification settings - Fork 0
/
NotifyMe.cpp
77 lines (65 loc) · 2.14 KB
/
NotifyMe.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
// Observer Pattern
#include <bits/stdc++.h>
using namespace std;
class StocksObserverInterface{
public:
virtual void update(string &messageFromObservable) = 0;
};
class StocksObservableInterface{
public:
virtual void add(StocksObserverInterface *observer) = 0;
virtual void remove(StocksObserverInterface *observer) = 0;
virtual void notify() = 0;
virtual void setStockcount(int count) = 0;
};
class StocksObserver : public StocksObserverInterface{
private:
string email_id;
StocksObservableInterface *observable;
public:
StocksObserver(string email, StocksObservableInterface* observable) : email_id(email), observable(observable) {
this->observable->add(this);
cout<<"I am subscribed to email notifications."<<endl;
}
void update(string &messageFromObservable){
cout<<"Mail sent to " + email_id + ": " + messageFromObservable<<endl;
}
void unsubscribe(){
this->observable->remove(this);
}
};
class StocksObservable : public StocksObservableInterface{
int stockCount = 0;
list<StocksObserverInterface*> observerList;
public:
void add(StocksObserverInterface *observer) override{
observerList.push_back(observer);
}
void remove(StocksObserverInterface *observer) override{
observerList.remove(observer);
}
void notify(){
auto it = this->observerList.begin();
string message = "Hurry Up! The product u wishlisted is back in stock.";
while(it!=this->observerList.end()){
(*it)->update(message);
it++;
}
}
void setStockcount(int count){
this->stockCount = count;
if(this->stockCount!=0) notify();
}
};
int main(){
StocksObservable *iphone = new StocksObservable();
StocksObservable *samsung = new StocksObservable();
StocksObserver *ob1 = new StocksObserver("[email protected]", iphone);
StocksObserver *ob2 = new StocksObserver("[email protected]", iphone);
StocksObserver *ob3 = new StocksObserver("[email protected]", samsung);
iphone->setStockcount(10);
samsung->setStockcount(5);
ob2->unsubscribe();
iphone->setStockcount(10);
return 0;
}