1. Chestnut in vernacular
A new library has been built in the city. Now a librarian called t is recruited. T knows the library's information about book renewal and borrowing. Now there are three students, a, B, C, who want to know the library book information and borrowing information in the next few months, so they go to t to register. When the library books are updated, t will send the updated information to the registered students. Three months later, C didn't need to know the book update information, so he went to t to cancel its information. So, in the future, only Party A and Party B will receive the news. A few months later, Ding also went to the library to register information, so in the future, Party A and Party B will receive the book update information.
2. principle
When we encounter a many to one dependency, we can use the observer pattern. The observer pattern has one subject and multiple observers. The observed provides the functions of registration, deletion and notification, and the observer provides the functions of data update and display.
Among the chestnuts above, t is an observed person. T provides the functions of registering identity information, deleting information, and sending notifications to methylethylpropadine. Methylethylpropadine is an observer, updating the information they get from t.
3. benefits
Independent encapsulation, no influence on each other: both the observer and the observed are encapsulated independently, and there is no interaction between the observers
Hot plug: add and remove observers dynamically while the software is running
4.Show in Code
class Subject(object): def __init__(self): self._observers = [] #Observer list #Registration function def attach(self, observer): if observer not in self._observers: self._observers.append(observer) #Deleting function def delete(self, observer): try: self._observers.remove(observer) except ValueError: pass #Notification function def notify(self, modifier=None): for observer in self._observers: if modifier != observer: observer.update(self) #Observed data source class Data(Subject): def __init__(self, name=''): Subject.__init__(self) self.name = name self._data = 0 def data(self): return self._data def dataset(self, value): self._data = value self.notify() #Observer class Viewer: def __init__(self, name=''): self._name = name def update(self, subject): print('my name is ', self._name, 'and', subject.name, '***', subject.data()) if __name__ == '__main__': data1 = Data('Administrators T') view1 = Viewer('nail') data1.attach(view1) view2 = Viewer('B') data1.attach(view2) view3 = Viewer('C') data1.attach(view3) print('data1 Initial value') print(data1.data()) print('change data1 Value') data1.dataset(5) print('Change again data1 Value') data1.dataset(10) print('delete view3 after') data1.delete(view3) data1.dataset(99)