-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreal.py
75 lines (50 loc) · 1.83 KB
/
real.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
from abc import ABCMeta, abstractmethod
class NewsPublisher:
def __init__(self):
self.__subscribers = []
self.__latestNews = None
def attach(self, subscriber):
self.__subscribers.append(subscriber)
def detach(self):
return self.__subscribers.pop()
def subscriber(self):
return [type(x).__name__ for x in self.__subscribers]
def notifySubscribers(self):
for sub in self.__subscribers:
sub.listen()
def addNews(self, news):
self.__latestNews = news
self.notifySubscribers()
def getNews(self):
return "Got News:", self.__latestNews
class Subscriber(metaclass=ABCMeta):
@abstractmethod
def listen(self):
pass
class SMSSubscriber(Subscriber):
def __init__(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def listen(self):
print(type(self).__name__, self.publisher.getNews())
class EmailSubscriber(Subscriber):
def __init__(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def listen(self):
print(type(self).__name__, self.publisher.getNews())
class AnyOtherSubscriber(Subscriber):
def __init__(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def listen(self):
print(type(self).__name__, self.publisher.getNews())
if __name__ == '__main__':
news_publisher = NewsPublisher()
for Subscribers in [SMSSubscriber, EmailSubscriber, AnyOtherSubscriber]:
Subscribers(news_publisher)
print("\nSubscribers:", news_publisher.subscriber())
news_publisher.addNews('Hello World!')
print("\nDetached:", type(news_publisher.detach()).__name__)
print("\nSubscribers:", news_publisher.subscriber())
news_publisher.addNews('My second news!')