"Design Patterns" Study Notes 7 - Observer Pattern

definition

The Observer pattern is one of the most frequently used design patterns and one of the easiest to understand. This pattern can be seen everywhere in life.
The observer pattern reference book defines the following:

Observer Pattern: Defines a one-to-many dependency between objects, so that whenever an object's state changes, its dependent objects are notified and automatically updated. Aliases for the observer pattern include the PublishSubscribe pattern, the Model/View pattern, the Source/Listener pattern, or the Dependents pattern. Observer pattern is an object behavior pattern

understand

Observer mode can be seen everywhere in life. The relationship between traffic lights at intersections and pedestrians and vehicles is an observer mode. Actors and audience are an observer mode. Even if one person speaks and others listen, it is also an observer mode. model.
To put it bluntly, it is an object that sends out a certain signal, and other objects will immediately make certain actions or reactions according to this object (doing nothing is also an action and reaction).
According to my understanding, I wrote a small example in which news websites update their homepage weather information according to the weather information of the Central Meteorological Observatory.

Observed

Here, the Central Meteorological Observatory acts as the observer, and the major websites act as observers. First, we define an interface for the observer (but from the perspective of implementing the observer mode, the interface can be omitted, but for better expansion, the interface programming is used here. ).

package patterntest.observerpattern.subject;
import java.util.ArrayList;
import java.util.List;
import patterntest.observerpattern.observer.WebSite;

/**
 * Weather station interface
 *
 * @author tzx
 * @date December 5, 2017
 */
public interface MyObservatory {
    /*
     * Store the observer collection
     */
    List weblist = new ArrayList();

    /**
     * Add new observer
     *
     * @param webSite
     */
    public void addWebSite(WebSite webSite);

    /**
     * delete observer
     *
     * @param webSite
     */
    public void removeWebSite(WebSite webSite);

    /**
     * Post weather information
     */
    public void pubMsg();

}

There are several necessary elements in this interface:
1. Save the collection of all the observer objects
2. The method of adding the observer object
3. The method of deleting the observer object
4. The method of publishing the information, also known as notifying the observer method

Then write an implementation class that implements the above interface and implement the abstract method:

package patterntest.observerpattern.subject;
import patterntest.observerpattern.observer.WebSite;
public class WeatherObservatory implements MyObservatory {

    @Override
    public void addWebSite(WebSite webSite) {
        weblist.add(webSite);

    }

    @Override
    public void removeWebSite(WebSite webSite) {
        weblist.remove(webSite);

    }

    @Override
    public void pubMsg() {
        for (WebSite webSite : weblist) {
            webSite.update();
        }

    }

}

The add and remove methods should not need to be said more, that is, adding and deleting elements to the list collection. The focus is on the pubMsg method, which is the method for publishing weather information here, which is the core of the observer pattern.
In this method, the collection that holds all the observer objects is traversed, and then the specific behavior method of each observer object is called. Of course, the logic here can be customized, not necessarily to notify all observers.

observer

With the observer, the next step is to create the observer. In the pubMsg method above, we call the update method of the WebSite object, but the corresponding object has not been defined yet.
The observer mode is generally a one-to-many relationship. Although it is no problem to say one-to-one, it seems to be overkill. So our observer here uses multiple objects. These objects are all observers, so they have a common parent class: the observer interface.

package patterntest.observerpattern.observer;

/**
 * Observer: website interface
 *
 * @author tzx
 * @date December 5, 2017
 */
public interface WebSite {
    /**
     * Take action based on observed information
     */
    public void update();
}

It can be seen that the definition of the observer interface is much simpler than that of the observed object. There is only one update method, which is the action taken after observing the state change of the observed object.
Observer is an abstract statement, and more specific observers are needed. Compared with the website interface here, I will give him two observer subclasses: Sina.com and Tencent.com.

package patterntest.observerpattern.observer;

public class Sina implements WebSite {

    @Override
    public void update() {
        System.out.println("Sina Weather Update");
    }

}
package patterntest.observerpattern.observer;

public class Tencent implements WebSite {

    @Override
    public void update() {
        System.out.println("Tencent Weather Update");
    }

}

What the two observers above are doing is too simple, so I won't say much. Next, Sina and Tencent started to observe the weather information of the Central Meteorological Observatory one after another, and then the Central Meteorological Observatory released new weather and notified the two major websites.

import patterntest.observerpattern.observer.Sina;
import patterntest.observerpattern.observer.Tencent;
import patterntest.observerpattern.observer.WebSite;
import patterntest.observerpattern.subject.MyObservatory;
import patterntest.observerpattern.subject.WeatherObservatory;
import patterntest.observerpattern.subject.WindObservatory;

/**
 * Observer mode test
 *
 * @author tzx
 * @date December 5, 2017
 */
public class ObserverTest {

    public static void main(String[] args) {
        // build the central weather station
        MyObservatory observatory = new WeatherObservatory();
        // Create Sina.com
        WebSite sina = new Sina ();
        // Sina.com began to observe the Central Meteorological Observatory's information announcement
        observatory.addWebSite(sina);
        // Create Tencent network
        WebSite tencent = new Tencent();
        // Tencent started to observe the information announcement of the Central Meteorological Observatory
        observatory.addWebSite(tencent);
        // Central Meteorological Observatory releases new weather information
        int i = 0;
        do {
        observatory.pubMsg();
            i++;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        } while (i

gist

According to the above examples and analysis, the observer pattern includes the following points:
1. An observable is required, also known as an observation target
2. The observation target needs to have a collection that holds all the observer objects
3. The observation target needs to have The method of adding the observer object
4. The observation target needs to have a method to delete the observer object
5. The observation target needs to have the method of publishing information, also known as the method of notifying the observer
object Methods

From the points summarized above, it should be easy to write an observer mode, but there are some points in the observer mode that need special explanation:
1. java provides support for the observer mode, the java.util package There are two interfaces Observer and Observable about the observer pattern. So if you want to write a class that observes the target, you can implement the Observable interface; to write an observer class, you can implement the Observer interface.
2. The implementation logic of the observer pattern may be slightly different from some understandings in reality. Just like the example of the meteorological station above, in principle, the meteorological station does not know which websites are observing meteorological information, and the website has the initiative to update the weather information. However, when the code implements the observer pattern, the observer is notified by the observation target, and the observation target needs to save all the observer objects.

Summarize

The observer pattern is relatively simple to understand and to implement. It may be because it is simple, so it can be seen everywhere in life, or it may be because it can be seen everywhere in life, so it is simple to understand.
All observer objects are saved in the observer mode. When abstract programming is used, only a collection of observer parent classes needs to be maintained, so that when new observers are added in the future, there is no need to change the observation target, which achieves a certain degree of relaxation. coupling.
But as you can see from the above example, the method of notifying the observer will traverse the collection of observer objects, and then call the corresponding method of each observer object in turn. So if this set of observers is very large, there are many observers, or the corresponding method does not end quickly. It will inevitably affect the overall efficiency, and there will also be a problem of data delay.
At the same time, although the observer can know the state of the observation target by passing parameters, it is impossible to know how the specific state of the observation target changes.

The demo source code can be downloaded from github: https://github.com/tuzongxun/mypattern

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325383303&siteId=291194637