-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver.cpp
More file actions
93 lines (84 loc) · 2.53 KB
/
observer.cpp
File metadata and controls
93 lines (84 loc) · 2.53 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
// observer design pattern
#include <iostream>
#include <string>
#include <list>
class Observer { // for weather specifically
public:
virtual ~Observer() {};
virtual void updateTemperature(double) = 0;
virtual void updateHumidity(double) = 0;
virtual void updateCondition(std::string) = 0;
};
class TemperatureDisplay : public Observer {
double temperature;
public:
TemperatureDisplay() {
temperature = 0;
}
double getTemp() {
return temperature;
}
void updateTemperature(double temp) override {
temperature = temp;
}
void updateHumidity(double humidity) override { }
void updateCondition(std::string condition) override {}
};
class HumidityDisplay : public Observer {
double humidity;
public:
HumidityDisplay() {
humidity = 0;
}
double getHumidity() {
return humidity;
}
void updateTemperature(double temp) override { }
void updateHumidity(double humidity) override {
this->humidity = humidity;
}
void updateCondition(std::string condition) override {}
};
class WeatherStation { // the subject
public:
WeatherStation(double temp = 0, double humidity=0, std::string condition = "") {
temperature = temp;
this->humidity = humidity;
this->condition = condition;
}
void subscribe(Observer* client) {
observers.push_back(client);
notify_change(); // update new subscriber
}
void unsubscribe(Observer* client) {
observers.remove(client); // linear time remove
notify_change(); // update new subscriber
}
void changeTemp(double temp) {
temperature = temp;
notify_change();
}
void notify_change() {
std::list<Observer*>::iterator iterator = observers.begin();
while (iterator != observers.end()) {
(*iterator)->updateTemperature(temperature);
(*iterator)->updateHumidity(humidity);
(*iterator)->updateCondition(condition);
++iterator;
}
}
private:
std::list<Observer*> observers;
double temperature;
double humidity;
std::string condition;
};
// assumes subjects/subscribers want ALL weather data
// alternatively, I could have inherited from an abstract (Weather station) - and just had separated subjects
int main() {
WeatherStation station1(10, 60, "cloudy");
TemperatureDisplay* screen = new TemperatureDisplay();
station1.subscribe(screen);
std::cout << "station temperature\n";
std::cout << screen->getTemp() << "\n";
}