-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path14_observer.py
74 lines (50 loc) · 1.35 KB
/
14_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
"""
Observer
- behavioral design pattern that lets you define a subscription mechanism to notify
multiple objects about any events that happen to the object they’re observing
"""
import abc
from random import randrange
class Publisher(abc.ABC):
@abc.abstractmethod
def subscribe(self, observer):
pass
@abc.abstractmethod
def unsubscribe(self, observer):
pass
@abc.abstractmethod
def notify(self):
pass
class ConcretePublisher(Publisher):
_observers = []
_state = None
def subscribe(self, observer):
self._observers.append(observer)
def unsubscribe(self, observer):
self._observers.remove(observer)
def notify(self):
print('Notifying observers...')
for observer in self._observers:
observer.update(self)
def operation(self):
self._state = randrange(0, 10)
print(f'state changed to {self._state}')
self.notify()
class Observer(abc.ABC):
@abc.abstractmethod
def update(self, publisher):
pass
class ObserverA(Observer):
def update(self, publisher):
if publisher._state <= 5:
print('ObserverA reacted to the event')
class ObserverB(Observer):
def update(self, publisher):
if publisher._state > 5:
print('ObserverB reacted to the event')
publisher = ConcretePublisher()
observer_a = ObserverA()
observer_b = ObserverB()
publisher.subscribe(observer_a)
publisher.subscribe(observer_b)
publisher.operation()