-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.py
66 lines (47 loc) · 1.7 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
class Observer:
"""Observer interface"""
def __init__(self):
self.name = None
def update(self):
print("Subclass must implement update()")
class Subscriber(Observer):
""" Subscriber class implemented the Observer interface"""
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
def update(self):
s = F"new youtube video released {self.name}"
print(s)
return s
class Publisher:
def register(self, subscriber: Subscriber) -> None:
raise NotImplemented("Subclass must implement register()")
def unregister(self, subscriber: Subscriber) -> None:
raise NotImplemented("Subclass must implement unregister()")
def notify(self) -> None:
raise NotImplemented("Subclass must implement notify()")
class ChannelPublisher(Publisher):
def __init__(self) -> None:
super().__init__()
self.subscribers = [] # observers
def register(self, subscriber: Subscriber) -> None:
self.subscribers.append(subscriber)
def unregister(self, subscriber: Subscriber) -> None:
self.subscribers.remove(subscriber)
def notify(self) -> None:
for subscriber in self.subscribers:
subscriber.update()
def main():
bob = Subscriber("Bob")
cody = Subscriber("Cody")
channelPublisher = ChannelPublisher()
channelPublisher.register(bob)
channelPublisher.register(cody)
channelPublisher.notify() # new youtube released, notify all
# subscribers/observers
channelPublisher.unregister(cody)
channelPublisher.notify()
channelPublisher.unregister(bob)
channelPublisher.notify()
if __name__ == '__main__':
main()