observer pattern in 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

#include <vector>

class ;
class Observer {
public:
virtual ~Observer() = default;
virtual void Update(Subject&) = 0;
};

class {
public:
virtual ~Subject() = default;
void Attach(Observer& o) { observers.push_back(&o); }
void Detach(Observer& o) {
observers.erase(std::remove(observers.begin(), observers.end(), &o));
}
void Notify() {
for (auto* o : observers) {
o->Update(*this);
}
}
private:
std::vector<Observer*> observers;
};

class ClockTimer : public Subject {
public:
void SetTime(int hour, int minute, int second) {
this->hour = hour;
this->minute = minute;
this->second = second;

Notify();
}

int GetHour() const { return hour; }
int GetMinute() const { return minute; }
int GetSecond() const { return second; }

private:
int hour;
int minute;
int second;
};

class DigitalClock: public Observer {
public:
explicit DigitalClock(ClockTimer& s) : subject(s) { subject.Attach(*this); }
~DigitalClock() { subject.Detach(*this); }
void Update(Subject& theChangedSubject) override {
if (&theChangedSubject == &subject) {
Draw();
}
}

void Draw() {
int hour = subject.GetHour();
int minute = subject.GetMinute();
int second = subject.GetSecond();

std::cout << "Digital time is " << hour << ":"
<< minute << ":"
<< second << std::endl;
}

private:
ClockTimer& subject;
};

class AnalogClock: public Observer {
public:
explicit AnalogClock(ClockTimer& s) : subject(s) { subject.Attach(*this); }
~AnalogClock() { subject.Detach(*this); }
void Update(Subject& theChangedSubject) override {
if (&theChangedSubject == &subject) {
Draw();
}
}
void Draw() {
int hour = subject.GetHour();
int minute = subject.GetMinute();
int second = subject.GetSecond();

std::cout << "Analog time is " << hour << ":"
<< minute << ":"
<< second << std::endl;
}
private:
ClockTimer& subject;
};

int main() {
ClockTimer timer;
DigitalClock digitalClock(timer);
AnalogClock analogClock(timer);

timer.SetTime(14, 41, 36);
}