Observer mode , Must contain “ The observer ” and “ Observed ” These two characters , And between the observer and the observed “ Observe ” Logical association of , When the observer changes , The observer will observe such changes , And respond accordingly . for example : Business data is the observed , The user interface is the observer .
actually , Observer mode is mostly a one to many relationship , Multiple observer objects can observe a certain observed object at the same time .
The realization idea of observer mode is : The core abstract class is used to manage all other classes that depend on it , When the core class changes , Proactively notify and update other classes .
When the number of customers decreases to the threshold , Sales will inform the factory to reduce production 、 At the same time, inform human resources to start layoffs , On the contrary, it increases .
class Observer:
""" Observer core class , Salesman """
def __init__(self):
self._number = None
self._department = []
@property
def number(self):
return self._number
@number.setter
def number(self, value):
self._number = value
print(' Current number of customers :{}'.format(self._number))
for obj in self._department:
obj.change(value)
print('------------------')
def notice(self, department):
""" Relevant departments """
self._department.append(department)
class Hr:
""" Observer class , Personnel department """
def change(self, value):
if value < 10:
print(" Personnel changes : layoffs ")
elif value > 20:
print(" Personnel changes : Expansion of staff ")
else:
print(" Personnel will not be affected ")
class Factory:
""" Observer class , Factory """
def change(self, value):
if value < 15:
print(" Production plan changes : production ")
elif value > 25:
print(" Production plan changes : Increase production ")
else:
print(" The production plan remains unchanged ")
if __name__ == '__main__':
observer = Observer()
hr = Hr()
factory = Factory()
observer.notice(hr)
observer.notice(factory)
observer.number = 10
observer.number = 15
observer.number = 20
observer.number = 25