python-Observer pattern

Source: Internet
Author: User

Description

There is such a situation: the company leaders to open a regular meeting on the day, he asked the Secretary to all the staff sent an e-mail, notice that the meeting canceled, the staff received the mail after the cancellation of the meeting will continue to return to their respective positions to start work. This includes an implicit thought: "One-to-many notification dependencies" between leaders and employees. A change in the state or behavior of an object will cause the state or behavior of other objects to change, and they will have linkage.

Viewer mode:

Defines a one-to-many dependency between objects, so that whenever an object state changes, its dependent objects are notified and automatically updated. The object being changed is called the observation target, and the object being notified is called the Observer. One observation target can correspond to multiple observers

Structure of the Observer pattern

The observer pattern consists of the following 4 roles: Subject (target) ConcreteSubject (Specific target) OBSERVER (Observer) Concreteobserver (specific observer)

Instance:
"""In the façade mode, we mentioned a fire alarm. At the time, we focused on reducing code duplication through encapsulation. Today, we will implement the fire alarm again from the perspective of business process implementation. """classAlarmsensor:defRun (self):Print("Alarm Ring ...")classWatersprinker:defRun (self):Print("Spray Water ...")classEmergencydialer:defRun (self):Print("Dial 119 ...")"""The above is the structure of the three sensor classes in the façade mode.
Careful analysis of the business, alarms, sprinklers, dials are "observing" the situation of the smoke sensor to do the reaction.
As a result, all three of them are observers, while smoke sensors are the object of observation.
According to the analysis, three classes are extracted to generalize the "observer" class and construct the Observer. The observers are as follows:"""classObserver:defUpdate (self):Passclassalarmsensor (Observer):defUpdate (self,action):Print("Alarm Got:%s"%action) Self.runalarm ()defRunalarm (self):Print("Alarm Ring ...")classWatersprinker (Observer):defUpdate (self,action):Print("sprinker Got:%s"%action) Self.runsprinker ()defRunsprinker (self):Print("Spray Water ...")classEmergencydialer (Observer):defUpdate (self,action):Print("Dialer Got:%s"%action) Self.rundialer ()defRundialer (self):Print("Dial 119 ...")"""The update interface is defined in the observer, if the observer State is more, or if each specific observer method is more,
Richer control can be obtained by using the update pass parameter. The following constructs are observed. """classobserved:observers=[] Action="" defAddobserver (self,observer): Self.observers.append (Observer)defNotifyall (self): forObsinchself.observers:obs.update (self.action)classSmokesensor (observed):defsetaction (self,action): Self.action=ActiondefIsfire (self):returnTrue"""The observed object is first added to the observer array, and if so, the observers are notified by Notifyall. The business code is as follows:"""if __name__=="__main__": Alarm=alarmsensor () Sprinker=watersprinker () dialer=Emergencydialer () smoke_sensor=smokesensor () smoke_sensor.addobserver (alarm) smoke_sensor.addobserver (sprinker) smoke_sensor.addobserver (di Aler)ifSmoke_sensor.isfire (): Smoke_sensor.setaction ("On fire!") Smoke_sensor.notifyall ()

Printing results:

Alarm Got:on fire!
Alarm Ring ...
Sprinker Got:on fire!
Spray water ...
Dialer Got:on fire!
Dial 119 ...

Pattern Benefits

The separation between the presentation layer and the data logic layer can be implemented to establish an abstract coupling support broadcast communication between the observation target and the observer, simplifying the difficulty of a one-to-many system design to conform to the open and closed principle, and adding the new specific observer without modifying the original system code, in the case of no correlation between the specific observer and the observation target. It's also convenient to add new observation targets.

Pattern disadvantage

All observers are notified that it takes a lot of time if there is a cyclic dependency that could cause a system crash there is no mechanism for the observer to know how the target object is changing, but only to know that the observation target has changed

Mode applicable environment

An abstract model has two aspects, one of which is dependent on another, encapsulating these two aspects in separate objects so that they can independently change and reuse one object changes will cause one or more other objects to change, and do not know how many of the objects will change, do not know who these objects are Need to create a trigger chain in the system

python-Observer Pattern

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.