Observer pattern
The Observer pattern (Observer pattern) is used when there is a one-to-many relationship between objects. For example, when an object is modified, its dependent objects are automatically notified. The observer pattern belongs to the behavioral pattern.
The Observer pattern is useful in scenarios such as State detection and event handling. This pattern ensures that a core object can be monitored by an unknown set of "Watcher" objects that may be expanding. Once a value of the core object changes, it lets all observer objects know that the situation has changed by calling the update () function. Each observer may be responsible for dealing with different tasks when the core object changes, and the core object does not know or care what these tasks are, and the observer is not aware of what the other observers are doing.
classInventory:"""docstring for ClassName""" def __init__(self): Self.observers=[] self._product=None self._quantity=0defAttach (Self,observer): Self.observers.append (Observer) @propertydefproduct (self):returnself._product @product. SetterdefProduct (self,value): Self._product=value self._update_observers () @propertydefQuantity (self):returnself._quantity @quantity. SetterdefQuantity (Self,value): Self._quantity=value self._update_observers ()def_update_observers (self): forObserverinchSelf.observers:observer ()classConsoleobserver:"""docstring for Consoleobserver""" def __init__(self, Inventory): self. Inventory=Inventorydef __call__(self):Print(self.) INVENTORY.PRODUCT)Print(self.) inventory.quantity)
Import observerpatterndemo>>> i=observerpatterndemo.inventory ()>>> c= Observerpatterndemo.consoleobserver (i)>>> I.attach (c)>>> i.product=" Hello world! " Hello world!0>>> i.quantity=999Hello world! 999
This object has two properties, and the _update_observers method is called when the assignment is performed. The work of this method is to traverse all the available observers so that they know something has changed. This calls the __CALL__ function directly to handle the change. This is not possible in many other programming languages, and in Python is a quick way to make our code more readable.
The observer pattern for Python design patterns