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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113 | from abc import ABC,abstractmethod
class Observer(ABC):
@abstractmethod
def update(self,args):
pass
class Subject(ABC):
@abstractmethod
def notifyAll(self):
pass
@abstractmethod
def addObserver(self,observer:Observer):
pass
@abstractmethod
def removeObserver(self,observer:Observer):
pass
class Notifier(ABC):
@abstractmethod
def notify(self,message):
pass
# implementations
class ProductInStock(Subject):
def __init__(self):
self.__observerList=[]
self._stockCount=0
def addObserver(self,observer:Observer):
self.__observerList.append(observer)
def removeObserver(self,observer:Observer):
self.__observerList.remove(observer)
def notifyAll(self):
for observer in self.__observerList:
observer.update(self.stockCount)
@property
def stockCount(self):
return self._stockCount
@stockCount.setter
def stockCount(self,value):
if value==self._stockCount: return
if value<0:
# raise ValueError("Stock Count cannot be negative")
print("Stock Count cannot be negative")
return
self._stockCount = value
self.notifyAll()
class MonitorObserver(Observer):
def __init__(self,notifyObj:Notifier):
self.notifyObj=notifyObj
def update(self,args):
self.notifyObj.notify("Product Updated: "+str(args))
class SMSNotifier(Notifier):
def __init__(self,contactNumber):
self.contactNumber=contactNumber
def notify(self,message):
print("Sending sms of : ",message, "to: ",self.contactNumber)
class EmailNotifier(Notifier):
def __init__(self,emailId):
self.emailId=emailId
def notify(self,message):
print("Sending E-Mail of : ",message, "to: ",self.emailId)
productInStock=ProductInStock()
smsNotifier=SMSNotifier("+1 123456")
monitor1=MonitorObserver(smsNotifier)
emailNotifier=EmailNotifier("testing@mail.com")
monitor2=MonitorObserver(emailNotifier)
productInStock.addObserver(monitor1)
productInStock.addObserver(monitor2)
productInStock.stockCount=4
print()
print()
productInStock.stockCount=-1
print()
print()
productInStock.stockCount=0
|