2. Observer Mode

Source: Internet
Author: User
Summary: The story of a weather station. Now we want to develop a meteorological monitoring system for a weather station. According to the customer's requirements, this monitoring system must be able to track the current weather conditions (temperature, humidity, atmospheric pressure) in real time ), it can be displayed on three different devices (current weather condition, weather statistics, and weather prediction ). The customer also hopes that this system can be used externally

Summary: The story of a weather station. Now we want to develop a meteorological monitoring system for a weather station. According to the customer's requirements, this monitoring system must be able to track the current weather conditions (temperature, humidity, atmospheric pressure) in real time ), it can be displayed on three different devices (current weather condition, weather statistics, and weather prediction ). The customer also hopes that this system can be used externally

Organize:

Weather Station story

Now we want to develop a meteorological monitoring system for a weather station. According to the customer's requirements, this monitoring system must be able to track the current weather conditions (temperature, humidity, atmospheric pressure) in real time ), it can be displayed on three different devices (current weather condition, weather statistics, and weather prediction ). The customer also hopes that the system can provide an external API so that any developer can develop their own display devices and then seamlessly connect them to the system. The system can update the data of all display devices in a unified manner. The customer also provides components for hardware devices that can access the weather station, as shown in:

It provides three methods (starting with get) to achieve real-time temperature, humidity, and atmospheric pressure, and a MeasurementsChanged () method. When any weather condition changes, this method is automatically triggered. Currently, this method is only an empty function, and the extended code needs to be expanded by ourselves. We do not need to consider how WeatherData gets weather conditions, or how the MeasurementsChanged () method is automatically triggered, we just need to think about how to do things related to the display device.

OK! Let's take a look at the implementation of this system and repeat the ideas:

1. The customer provides a way to obtain real-time weather conditions.

2. The MeasurementsChanged () method is automatically called when the weather condition changes.

3. The system must display the weather conditions, weather statistics, and weather forecasts in three modes. The information displayed must be synchronized with the latest weather conditions in real time.

4. The system must also support the scalability of the display mode, and users can add or remove different display modes at will.

Based on the above information, we will probably think of implementing this system as follows:

// Pseudocode

Public class WeatherData

{

// Instantiate the display device (omitted)

Public void MeasurementsChanged ()

{

Float temp = getTemperature (); // get the temperature

Float humidity = getHumidity (); // obtain humidity

Float pressure = getPressure (); // obtain the pressure

CurrentConditionsDisplay. update (temp, humidity, pressure); // synchronously display the current weather condition

StatisticsDisplay. update (temp, humidity, pressure); // synchronously display weather statistics

ForecastDisplay. update (temp, humidity, pressure); // displays the weather forecast information synchronously.

}

}

Because the customer has provided us with real-time data and a trigger mechanism for data update, what we need to do is to provide the latest data to different display devices, the above Code seems to be able to basically solve the problem. Haha!

Interface-oriented programming, rather than implementation programming ." In this way, the system cannot dynamically add or remove different display devices without modifying the code. In other words, the display device-related part is the most unstable part of the system and should be isolated separately, that is, another principle learned previously: "find the changed part of the system, separate the changed part from other stable parts." So what should we do? Well, since this article is about the observer model, we must use it to end the battle! Next, let's take a look at the observer mode ~

This is the observer mode.

Let's take a look at the official definition:

The Observer PatternDefines a one-to-define dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. (The Observer mode defines a one-to-many dependency between objects, so that every time an object changes its state, all objects dependent on it will be notified and automatically updated)

What? This is a standard definition of super classics, such as fake replacement! Don't you understand? Let's take a look at the following class diagram ~

Subject (object interface observed)

L define the unified interface of ConcreteSubject;

L each Subject can have multiple observers;

ConcreteSubject (object to be observed)

L maintain a list of references to all specific observers;

L when the status changes, a notification is sent to all registered observers.

Observer (Observer Interface)

L define the unified interface of ConcreteObserver;

L defines an update () method, which is called when the state of the object to be observed changes.

ConcreteObserver (Specific observer)

L maintain a reference to ConcreteSubject;

L synchronization between a specific status and ConcreteSubject;

L implements the Observer interface and receives ConcreteSubject notifications through the update () method.

How are you doing? The following is a sequence chart ~

Haha! I still don't want to understand why the official stuff is always incomprehensible. It seems that it is not an official life! In fact, the Observer mode is very simple, and examples in real life can be seen everywhere. For example, watching TV: a certain audience is a standard ConcreteObserver (Specific observers comply with the unified Observer interface, that is to say, all viewers must watch the program through TV. The TV program is Subject (the interface of the object to be observed, which is embodied in wireless TV signals, the programs on different channels are different ConcreteSubject (different channels have different programs). The audience can decide whether to watch the registerObserver or removeObserver ), the changes in TV programs will automatically update the content of all viewers. How is it? This time I understand it!

In addition, the Observer mode is also called the Publish-subscribe mode (Publishers + Subscribers = Observer Pattern). Just like watching TV, subscribing to a newspaper is also a very intuitive example. Someone publishes a newspaper (Publish = Subject, someone subscribes to a newspaper (Subscribe = Observer). The subscriber can regularly receive the latest newspaper, and the subscriber can unsubscribe it at any time.

Now everyone should have a basic understanding of the observer model. We will use this model to solve the problem of which meteorological station. In the application scenarios of meteorological stations, WeatherData can be viewed as ConcreteSubject, while different display devices can be viewed as ConcreteObserver, that is, display devices can observe WeatherData objects, if the WeatherData object has any status changes, the device's data information is immediately updated. This seems to be very reliable. Let's implement it in detail, starting with the overall structure, as shown in the following class diagram:

The implementation method is exactly the same as that mentioned earlier. It only defines a unified interface for all display devices. This interface defines a display () method, that is to say, in the future, all objects implementing the Observer and DisplayElement interfaces can be used as terminal display devices of the meteorological monitoring system. Different users can customize their display modes in the display () method. To prevent confusion, only one specific display device object is drawn, namely CurrentConditionsDisplay, which has the same level as StatisticsDisplay and ForcastDisplay, which have the same structure. The following code further describes the implementation of the observer-based meteorological monitoring system.

ISubject:

public interface Subject {public void registerObserver(Observer observer);public void removeObserver(Observer observer);public void notifyObservers();}


There seems to be nothing to say about this code, because it has already been said a lot.

IObserver:

public interface Observer {public void update(float temp, float humidity, float pressure);}

Here we define three parameters for the update () method that correspond to different meteorological data.

DisplayElement:

public interface DisplayElement {public void display();}


This class is also super simple and there is nothing to explain.

WeatherData:

public class WeatherData implements Subject {private ArrayList observers;private float temp;private float humidity;private float pressure;public WeatherData() {this.observers = new ArrayList();}@Overridepublic void notifyObservers() {for (int i = 0; i < observers.size(); i++) {Observer observer = (Observer) observers.get(i);observer.update(temp, humidity, pressure);}}@Overridepublic void registerObserver(Observer observer) {observers.add(observer);}@Overridepublic void removeObserver(Observer observer) {int i = observers.indexOf(observer);if (i >= 0) {observers.remove(i);}}public void measurementsChanged() {notifyObservers();}public void setMeasurements(float temp, float humidity, float pressure) {this.temp = temp;this.humidity = humidity;this.pressure = pressure;measurementsChanged();}}


This class is the specific implementation of ISubject. The ArrayList is used internally to record all registered observers. The SetMeasurements () method is used to simulate the aforementioned automatic triggering of MeasurementsChanged () when the weather condition changes () method.

CurrentConditionsDisplay:

public class CurrentConditionDisplay implements Observer, DisplayElement {private Subject weatherData;private float temp;private float humidity;public CurrentConditionDisplay(Subject weatherData) {this.weatherData = weatherData;weatherData.registerObserver(this);}@Overridepublic void update(float temp, float humidity, float pressure) {this.temp = temp;this.humidity = humidity;display();}@Overridepublic void display() {System.out.println("CurrentConditionDisplay   temp = " + temp+ " humidity = " + humidity);}}



This class is the specific implementation of IObserver and IDisplayElement, representing the specific display device object that displays the current weather condition. It maintains an ISubject type variable internally, this variable is initialized in the CurrentConditionsDisplay constructor and ISubject is called at the same time. the registerObserver () method to subscribe to ISubject.

StatisticsDisplay and ForcastDisplay:

public class ForecastDisplay implements Observer, DisplayElement {private Subject weatherData;private float temp;private float humidity;private float pressure;public ForecastDisplay(Subject weatherData) {this.weatherData = weatherData;weatherData.registerObserver(this);}@Overridepublic void update(float temp, float humidity, float pressure) {this.temp = temp;this.humidity = humidity;this.pressure = pressure;display();}@Overridepublic void display() {System.out.println("ForecastDisplay   temp = " + temp + " pressure = "+ pressure);}}



The StatisticsDisplay code is similar.

Test code:

public class WeatherTest {public static void main(String[] args) {WeatherData weatherData = new WeatherData();CurrentConditionDisplay currentDisplay = new CurrentConditionDisplay(weatherData);ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);weatherData.setMeasurements(80f, 90f, 30.4f);weatherData.setMeasurements(100f, 99f, 40.0f);}}

.. Use the built-in observer mode of JDK

If the built-in Observer mode of java is used, Subject must inherit the java. util. Observable class and the Observer implements the java. util. Observer interface. The specific code is as follows:

Public class WeatherData extends Observable {private float temp; private float humidity; private float pressure; public WeatherData () {// we do not need to define the data structure for storing the observer at this time .} Public void measurementsChanged () {setChanged (); yyobservers (); // call the setChanged method before calling the yyobservers method, the notifyObservers code in the/*** Observable class is as follows: public void policyobservers (Object * arg) {Object [] arrLocal; ** synchronized (this) {if (! Changed) return; arrLocal = obs. toArray (); * clearChanged ();} ** for (int I = arrLocal. length-1; I> = 0; I --) * (Observer) arrLocal [I]). update (this, arg) ;}}** methods in the Observable class: * protected synchronized void setChanged () {changed = true;} **/} public void setMeasurements (float temp, float humidity, float pressure) {this. temp = temp; this. humidity = humidity; this. pressure = pressure; measurementsChanged ();} public float getTemp () {// define this method, only because the observer uses it to "pull" The data return temp;} public float getHumidity () {return humidity;} public float getPressure () {return pressure;} the Observer's definition is as follows: public class CurrentConditionDisplay implements Observer, DisplayElement {private Observable weatherData; private float temp; private float humidity; public CurrentConditionDisplay (Observable weatherData) {this. weatherData = weatherData; weatherData. addObserver (this) ;}@ Overridepublic void display () {System. out. println ("CurrentConditionDisplay temp =" + temp + "humidity =" + humidity);} @ Overridepublic void update (Observable obs, Object arg) {if (obs instanceof WeatherData) {WeatherData weatherData = (WeatherData) obs; this. temp = weatherData. getTemp (); this. humidity = weatherData. getHumidity (); display ();}}}


The remaining code is similar to the interface defined above.


Application scenarios and advantages and disadvantages

The above has already made a more detailed introduction to the observer model. In other words, there is no perfect person, and the model is not omnipotent. We should use the design model to solve our actual problems, you must be familiar with the application scenarios and advantages and disadvantages of the Mode:

Application scenarios of observer mode:

1. Update the status of an object. Other objects must be updated synchronously, and the number of other objects can be changed dynamically.

2. The object only needs to notify other objects of its own updates without knowing the details of other objects.

Advantages of observer mode:

1. Subject and Observer are loosely coupled and can be changed independently.

2. When a Subject sends a broadcast notification, it does not need to specify a specific Observer. The Observer can decide whether to subscribe to the Subject notification.

3. comply with most GRASP principles and common design principles, with high cohesion and low coupling.

Observer pattern defects:

1. Loose coupling causes the code relationship to be less obvious and sometimes hard to understand. (Nonsense)

2. If a Subject is subscribed by a large number of Observer users, it may be efficient during broadcast notifications. (After all, it is just a simple traversal)


Reference: http://www.cnblogs.com/justinw/archive/2007/05/02/734522.html! Comments


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.