-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq5.cpp
92 lines (74 loc) · 1.78 KB
/
q5.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
#include <iostream>
#include <vector>
using namespace std;
class Observer;
class Observed {
vector<Observer *> observers;
public:
void subscribe(Observer*);
void notify();
};
class Observer {
public:
virtual void takeAction() = 0;
};
class Clock : public Observed {
private:
const unsigned int MAXCOUNT;
public:
Clock(unsigned int);
void tick();
};
class Device : public Observer {
protected:
unsigned int count;
public:
Device(unsigned int c) : count(c) {}
};
class IncrementerDevice : public Device {
public:
IncrementerDevice();
void takeAction();
};
class MultiplierDevice : public Device {
const unsigned int MULTIPLIER;
public:
MultiplierDevice(unsigned int);
void takeAction();
};
/////////////Methods of class Observed ////////////////////
void Observed:: subscribe(Observer* o) {
observers.push_back(o);
}
void Observed::notify() {
for (unsigned int i = 0; i < observers.size(); i++) {
observers[i]->takeAction();
}
}
/////////////Methods of class Clock //////////////////////
Clock::Clock(unsigned int c) : MAXCOUNT (c) {}
void Clock::tick() {
for (unsigned int i = 0; i < MAXCOUNT; i++) {
notify();
}
}
/////////////Methods of class IncrementerDevice //////////////////////
IncrementerDevice::IncrementerDevice() : Device(0) {}
void IncrementerDevice::takeAction() {
cout << "Incrementer::count = " << count++ << endl;
}
/////////////Methods of class MultiplierDevice //////////////////////
MultiplierDevice::MultiplierDevice(unsigned int m) : Device(1), MULTIPLIER(m) {}
void MultiplierDevice::takeAction() {
cout << "Multiplier::count = " << count << endl;
count *= MULTIPLIER;
}
int main() {
Clock clock(10);
IncrementerDevice inc;
MultiplierDevice mul(2);
clock.subscribe(&inc);
clock.subscribe(&mul);
clock.tick();
return 0;
}