-
Notifications
You must be signed in to change notification settings - Fork 0
/
observer.py
95 lines (69 loc) · 2.02 KB
/
observer.py
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
"""
Publisher + subscriber = Observer Pattern
"""
"""
We are designing a weather station ,which outsource the data
that data is used to power some displays.
Weather station has following data:
1: Temprature
2: Pressure
3: Humidity
Display changes the data whenever the data is updated at published end
"""
from abc import ABCMeta, abstractmethod
class Source(metaclass=ABCMeta):
@abstractmethod
def get_temprature(self):
NotImplementedError
@abstractmethod
def get_pressure(self):
NotImplementedError
@abstractmethod
def get_humidity(self):
NotImplementedError
@abstractmethod
def measurement_changed(self):
NotImplementedError
class Publisher(metaclass=ABCMeta):
@abstractmethod
def update_displays(self):
NotImplementedError
class Subscriber(metaclass=ABCMeta):
@abstractmethod
def display(self):
NotImplementedError
class WeatherStation(Source):
@property
def get_temprature(self):
return 45
@property
def get_pressure(self):
return .75
@property
def get_humidity(self):
return 94
def measurement_changed(self, weather_object):
weather_object.update_displays(self.get_temprature, self.get_pressure, self.get_humidity)
class WeatherObject(Publisher):
def __init__(self):
self.displays = []
def add_display(self, display):
self.displays.append(display)
def remove_display(self, display):
self.displays.remove(display)
def update_displays(self, temp, press, humid):
for display in self.displays:
display.display(temp, press, humid)
class DisplayScreen(Subscriber):
def display(self, temp, press, humid):
print(temp, press, humid)
if __name__ == '__main__':
station = WeatherStation()
pub = WeatherObject()
d1 = DisplayScreen()
d2 = DisplayScreen()
d3 = DisplayScreen()
pub.add_display(d1)
pub.add_display(d2)
pub.add_display(d3)
station.measurement_changed(pub)