The observer mode is one of the most common design patterns. it aims to establish an abstract coupling between the object and the observer to reduce the coupling between objects, here, let's take a look at the sample of the observer mode structure in the Python program.
Observer Mode definition
Defines one-to-multiple dependencies between objects. in this way, when an object changes its status, all its dependencies will be notified and automatically updated. The Observer Mode provides an object design that allows loose coupling between the subject and the Observer.
Design principles
Efforts are made to design loose coupling between interaction objects. The reason why the loosely coupled design enables us to build an elastic system and respond to changes is that the dependency between objects is minimized.
Schema structure and description
# Observer pattern class subject (): def _ init _ (self, dat): self. listobj = list () # The list variable in the topic is used to store the observer self. dat = dat # When the data in the topic changes, notify the observer def registerObject (self, obj): self. listobj. append (obj) # implement the topic subscription function def removeObject (self, obj): pass def notifyObservers (self): # notify each observer that the data has changed, the observer needs to update his own data for I in range (len (self. listobj): self. listobj [I]. update () def setdat (self, new_dat): # set data if self. dat! = New_dat: self. dat = new_dat self. policyobservers () class observer (): # observer def _ init _ (self, sub): # The observer needs to subscribe to the topic self when initializing. sub = sub self. sub. registerObject (self) self. number = self. sub. dat def update (self): # The Observer updates self. number = self. sub. dat def display (self): print self. number if _ name _ = "_ main _": su = subject (10) ob1 = observer (su) ob1.display () ob2 = observer (su) ob2.display () su. setdat (11) ob1.display () ob2.display ()
For more articles about the observer mode structure in Python, refer to the PHP Chinese network!