-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObserver Design Pattern
73 lines (60 loc) · 1.63 KB
/
Observer Design Pattern
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
/*
When you are interested in state of an object and want to get notified when there is a change.
The object being watched is called observable (subject) and whatever watches it, called observer.
*/
#include <iostream>
#include <vector>
// Observer interface
class Observer {
public:
virtual void update(float temperature, float humidity, float pressure) = 0;
};
// Subject (WeatherStation) class
class WeatherStation {
private:
float temperature;
float humidity;
float pressure;
std::vector<Observer*> observers;
public:
void registerObserver(Observer* observer) {
observers.push_back(observer);
}
void removeObserver(Observer* observer) {
// You can implement the removal logic if needed.
}
void notifyObservers() {
for (Observer* observer : observers) {
observer->update(temperature, humidity, pressure);
}
}
void setMeasurements(float temp, float hum, float press) {
temperature = temp;
humidity = hum;
pressure = press;
notifyObservers();
}
};
// Concrete Observer
class Display : public Observer {
public:
void update(float temperature, float humidity, float pressure) {
std::cout << "Display: Temperature = " << temperature
<< "°C, Humidity = " << humidity
<< "%, Pressure = " << pressure << " hPa"
<< std::endl;
}
};
int main() {
WeatherStation weatherStation;
// Create displays
Display display1;
Display display2;
// Register displays as observers
weatherStation.registerObserver(&display1);
weatherStation.registerObserver(&display2);
// Simulate weather data updates
weatherStation.setMeasurements(25.5, 60, 1013.2);
weatherStation.setMeasurements(24.8, 58, 1014.5);
return 0;
}