Observer Pattern)

Source: Internet
Author: User

Observer Pattern)

 

Overview

The observer mode is used to establish a dependency between an object and an object. When an object changes, other objects are automatically notified, and other objects are responded accordingly. In the observer mode, the changed object is called the observation object, and the notified object is called the observer. One observation object can correspond to multiple observers, and there can be no mutual relationship between these observers, you can add and delete observers as needed to make the system more scalable. A software system often requires that some other objects change accordingly when the state of an object changes. There are many design solutions to achieve this, but in order to make the system easy to reuse, we should choose a low coupling design. Reducing the coupling between objects is conducive to the reuse of the system, but at the same time, the designer needs to make the objects with low Coupling Degree consistent with each other to ensure high collaboration. The observer pattern is the most important in various design schemes that meet this requirement.

Core

Concept:Defines a one-to-multiple dependency between objects, so that each time an object's status changes, its dependent objects are notified and automatically updated. The alias of observer mode includes Publish/Subscribe mode, Model/View mode, Source/Listener mode, and Dependents) mode. The observer mode is an object behavior mode.

Important core modules of the observer mode structure:

Abstract topic)

Abstract topic roles store all references to observer objects in a aggregation (such as an ArrayList object). Each topic can have any number of observers. Abstract topic provides an interface to add and delete observer objects. Abstract topic roles are also called abstract observer roles.

ConcreteSubject)

Stores the status in a specific observer object. When the internal status of a specific subject changes, a notification is sent to all registered observers. A topic role is also called a Concrete Observable role.

Abstract Observer (Observer)

Define an interface for all the specific observers to update themselves when they receive notifications of the topic. This interface is called the update interface.

ConcreteObserver)

The storage status is the same as that of the topic. The specific observer role implements the update interface required by the abstract observer role to coordinate its status with the status of the topic. If necessary, a specific observer role can maintain a reference pointing to a specific topic object.

Use Cases

An abstract model has two aspects, one of which depends on the other. These two aspects are encapsulated in independent objects so that they can be changed and reused independently.

An object changes one or more other objects, but does not know how many objects will change or who these objects are.

You need to create A trigger chain in the system. The behavior of object A will affect object B, and the behavior of object B will affect Object C ......, You can create a chain trigger mechanism in observer mode.

Program ape instance

Simple Example:

The following is a simple observer mode. I will not explain it too much:

Package yanbober. github. io; import java. util. arrayList; import java. util. list; // abstract Observer Angle class interface Observer {void update (String state);} // specific Observer Angle class ProgramMonkeyObserver implements Observer {@ Override public void update (String state) {System. out. println (Programer look the SDK download process is: + state) ;}// abstract topic Angle class abstract class Subject {private List
  
   
List = new ArrayList <> (); public void attach (Observer observer) {list. add (observer);} public void detach (Observer observer) {list. remove (observer);} public void motifyObservers (String newState) {for (Observer observer: list) {observer. update (newState) ;}}// class SDKDownloadSubject extends Subject {public void netProcessChange (String data) {this. motifyObservers (data) ;}// client public class Main {public static void main (String [] args) {SDKDownloadSubject sdkDownloadSubject = new SDKDownloadSubject (); observer observer = new ProgramMonkeyObserver (); sdkDownloadSubject. attach (observer); sdkDownloadSubject. netProcessChange (1%); sdkDownloadSubject. netProcessChange (51%); sdkDownloadSubject. netProcessChange (100% );}}
  

Upgrade equipment:The pull mode of the observer mode.

Example of observer mode of Push mode:

The topic object pushes the detailed information of the topic to the observer, regardless of whether the observer needs it or not. The pushed information is usually all or part of the data of the topic object.

The simple example above is actually an example of the observer mode, which is not described here.

Example of the observer mode of Pull Mode:

When a topic object notifies the observer, it only transmits a small amount of information. If the observer needs more specific information, the observer takes the initiative to get it from the topic object, which is equivalent to pulling data from the topic object. In general, the implementation of this model will pass the topic object itself to the observer through the update () method, so that the observer can obtain the data through this reference when it needs to obtain the data.

The following code is an example of modifying the push mode (simple example) to pull mode. I will not explain it too much here:

Package yanbober. github. io; import java. util. arrayList; import java. util. list; // abstract Observer Angle class interface Observer {void update (Subject subject);} // The specific Observer Angle class ProgramMonkeyObserver implements Observer {@ Override public void update (Subject subject) {String state = (SDKDownloadSubject) subject ). getState (); System. out. println (Programer look the SDK download process is: + state) ;}// abstract topic Angle class abstract class Subject {private List
  
   
List = new ArrayList <> (); public void attach (Observer observer) {list. add (observer);} public void detach (Observer observer) {list. remove (observer);} public void motifyObservers () {for (Observer obs: list) {obs. update (this) ;}}// class SDKDownloadSubject extends Subject {private String mState; public String getState () {return mState;} public void netProcessChange (String data) {mState = data; this. motifyObservers () ;}}// client public class Main {public static void main (String [] args) {SDKDownloadSubject sdkDownloadSubject = new SDKDownloadSubject (); Observer observer = new ProgramMonkeyObserver (); sdkDownloadSubject. attach (observer); sdkDownloadSubject. netProcessChange (1%); sdkDownloadSubject. netProcessChange (51%); sdkDownloadSubject. netProcessChange (100% );}}
  

Continue to upgrade the observer Mode Supported by the awesome Java standard:

In the Java. util library of the java language, an Observable class and an Observer interface are provided to support the Observer mode of the Java language.

The Observer interface defines only one update () method. When the State of the object to be observed changes, the notifyObservers () method of the object to be observed calls this method.

The Observable class is the base class of the observer class. Java. util. Observable provides public methods to support observer objects. Two of these methods are very important to the Observable subclass: setChanged () and notifyObservers (). The first method, after setChanged () is called, an internal tag variable is set to indicate that the status of the object to be observed has changed. The second is yyobservers (). When this method is called, the update () method of all registered observer objects is called so that these observer objects can update themselves.

The following example shows how to use the observer Mode Supported by the Java library. The specific details are not explained:

Package yanbober. github. io; import java. util. observable; import java. util. observer; // Observer class ProgramMonkeyObserver implements Observer {public ProgramMonkeyObserver (Observable obs) {obs. addObserver (this) ;}@ Override public void update (Observable o, Object arg) {System. out. println (Programer look the SDK download process is: + (SDKDownloadObservable) o ). getState () ;}}// class SDKDownloadObservable extends Observable {private String mState; public String getState () {return mState;} public void netProcessChange (String data) {mState = data; this. setChanged (); this. notifyObservers () ;}}// client public class Main {public static void main (String [] args) {SDKDownloadObservable sdkDownloadObservable = new SDKDownloadObservable (); new ProgramMonkeyObserver (listener); listener. netProcessChange (1%); sdkDownloadObservable. netProcessChange (51%); sdkDownloadObservable. netProcessChange (100% );}}

Continue upgrade-interaction between objects (event processing ):

With the above three example of the progressive observer mode, we still need to continue to explore and upgrade... Go, go, go...

Do you still remember the basic examples of the front edge? You may find that the interface used in Android development for operations like Fragment and Activity, and Fragment interaction is the observer mode, it's just a little different from the writing method here. Haha, this is what we will talk about next.

In the DEM model, the target role (such as the interface component) is responsible for releasing events, while the observer role (event handler) can subscribe to events that interest the target. When a specific target generates an event, it notifies all subscribers. The Event publisher is called the Event Source, and the subscriber is called the Event Listener. In this process, you can also use the Event Object) to transmit event-related information. event processing can be implemented in the implementation class of event listeners. Therefore, event listening objects can be called event processing objects. The event source object, event listening object (event processing object), and event object constitute three elements of the Java event processing model.

Let's go! isn't the powerful Google Android source code control xxxListener in similar mode !!! Haha, that's the duang !!! This does not mean that in event processing, we usually use a one-to-one observer mode, rather than a one-to-many observer mode!

The instance program is skipped, and the event model is everywhere in Android, regardless of the source code or self-writing code.

The revolution has not yet succeeded, and comrades still need to work hard. Continue to upgrade the Observer Model (MVC software framework model ):

The observer mode is also applied in the Model-View-Controller architecture, which is well-known in the software industry. MVC is an architecture mode that includes three roles: Model ), view and Controller ). The model corresponds to the observation target in the Observer mode, while the view corresponds to the observer. The controller can act as the intermediary between the two. When the data at the model layer changes, the view layer automatically changes its display content.

Summary

Advantages of observer mode:

The observer mode establishes an abstract coupling between the observer and the observer. What the observer role knows is a specific observer list. Each specific observer conforms to an abstract observer interface. The observer does not know any specific observer, but only knows that they all have a common interface. Since the observer and observer are not closely coupled, they can belong to different abstract layers. If the object is thrown together by both the observer and the observer, the object must span the abstract and concrete layers.

Disadvantages of observer mode:

If an object to be observed has many direct and indirect observers, it takes a lot of time to notify all the observers. If there is a circular dependency between the observer, the observer will trigger a circular call between them, resulting in system crash. Pay special attention to this when using the observer mode. If the notification to the observer is asynchronously delivered through another thread, the system must ensure that the delivery is carried out in the correct way. Although the observer mode can enable the observer to know the changes of the observed object at any time, the observer mode does not have a mechanism to let the observer know how the observed object changes.

 

Related Article

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.