Study Notes -- Observer mode in Design Mode

Source: Internet
Author: User

The scenario in head first is::

The customer needs such an app: A wheatherdata class can obtain meteorological information (temperature, humidity, pressure and so on) from the weather station ). once the information changes, three bulletin boards (currentconditionbulletin, statisticsbulletin, and forecastbulletin) of the weather station will be updated. In addition, you can add, delete, and change your bulletin boards at any time ).

The customer gave the wheatherdata class diagram:

Based on the preceding descriptions and class diagrams, we know that:

1. getter can obtain meteorological information.

2. Once the meteorological information changes, call the measurementschanged () method to update all the billboards.

3. Now we need three billboards.

4. Customer can define their own dashboard

First, let's look at a poor implementation:

public class WeatherData {               public void MeasurementsChanged()        {            float temp = getTemperature();             float humidity = getHumidity();             float pressure = getPressure();            currentConditionsDisplay.update(temp, humidity, pressure);             statisticsDisplay.update(temp, humidity, pressure);            forecastDisplay.update(temp, humidity, pressure);        }}

Why not? You can start with the following design principles:

1. Find the changed part of the program and isolate it from the fixed part.

In this scenario, the type and quantity of the bulletin board are changed. In this bad example, we need to change the type and quantity of the bulletin board and modify the wheatherdata class. How can I modify the number and type of the bulletin board without modifying the wheatherdata class?

2. Interface Programming, not implementation programming

Obviously, statisticsdisplay, statisticsdisplay, and forecastdisplay are all specific programming implementations. If we add and modify the bulletin board later, we must modify this program. In addition, the names and parameters of the three methods (Update () are the same. Is a unified interface feasible?

You can have a simple understanding of the Observer Model Based on the newspaper subscription business:

Observer pattern class diagram:

Subject

You can also use the topic interface to register an object as an observer or delete the object from the observation. Each topic can have multiple observers.

Concretesubject

A specific topic implements the topic interface. In addition to registration and revocation, a specific topic also implements the yyobservers () method. This method is used to make all the observers when the topic status changes. You may also set and obtain the status of a topic.

Observer

All potential observers must implement the observer interface, which is called only when the topic changes.

Concreteobserver

The specific observer can be any class that implements the observer interface. The observer must register a specific topic and receive updates.

Basic principle: efforts are made to design loose coupling between interaction objects.

Definition of observer mode: The Observer mode defines one-to-multiple dependencies between objects. In this way, when an object changes state, all its dependent persons will receive notifications and update them automatically.

In observer mode, what is the one-to-many relationship?

In this mode, a topic is a stateful object that can be controlled.

On the other hand, the observer uses these states, although they do not belong to them. There are multiple observers who rely on themes to tell them when the theme status has changed.

This produces a relationship between a "topic" and multiple "observers ".

What is the power of loosely coupled design?

When two objects are loosely coupled, they can still interact, but they are not very clear about each other's details. The observer mode provides an object design that allows loose coupling between the subject and the observer.

Next we will draw an opening line based on the Observer pattern.Wheatherstation class diagram:

The Code is as follows:

Isubject:

import org.jpatterns.gof.ObserverPattern;@ObserverPattern(comment="ISubject: Interface of Observer Pattern")public interface ISubject {void registerObserver(IObserver o);void deleteObserver(IObserver o);void notifyObservers();}

Iobserver:

import org.jpatterns.gof.ObserverPattern;@ObserverPattern(comment="IObserver: Interface of Observer Pattern")public interface IObserver {void update(float temp, float humidity, float pressure);}

Wheatherdata that implements the isubject interface:

import java.util.ArrayList;import org.jpatterns.gof.ObserverPattern;@ObserverPattern(comment = "WheatherData: Concrete Subject of Observer Pattern")public class WheatherData implements ISubject {private ArrayList<IObserver> observers;private float temperature;private float humidity;private float pressure;public WheatherData() {this.observers = new ArrayList<IObserver>();}@Overridepublic void registerObserver(IObserver o) {observers.add(o);}@Overridepublic void deleteObserver(IObserver o) {if (observers.indexOf(o) >= 0) {observers.remove(o);}}@Overridepublic void notifyObservers() {for (int i = 0; i < observers.size(); i++) {IObserver observer = observers.get(i);observer.update(temperature, humidity, pressure);}}public void measurementsChanged() {this.notifyObservers();}public void setMeasurements(float temperature, float humidity, float pressure) {this.temperature = temperature;this.humidity = humidity;this.pressure = pressure;this.measurementsChanged();}}

A bulletin implementing the iobserver interface:

public class CurrentConditionsBulletin implements IObserver, IDisplayElement {private float temperature;private float humidity;private ISubject wheatherData;public CurrentConditionsBulletin(ISubject wheatherData) {this.wheatherData = wheatherData;wheatherData.registerObserver(this);}@Overridepublic void update(float temp, float humidity, float pressure) {this.temperature = temp;this.humidity = humidity;this.display();}@Overridepublic void display() {System.out.println("Current Conditions: " + this.temperature+ "F Degrees and " + this.humidity + "% Humidity");}}

Create a weather station and run the program:

Public class wheatherstation {public static void main (string [] ARGs) {wheatherdata = new wheatherdata (); iobserver O1 = new currentconditionsbulletin (wheatherdata ); iobserver O2 = new statisticsbulletin (wheatherdata); iobserver O3 = new forecastbulletin (wheatherdata); iobserver O4 = new custombulletin (wheatherdata); // custom partition (20, 20, 20, 20 );}}

I have omitted many comments. If you want to understand them well, I suggest you go to headfirst. To be honest, this book is really great!

In fact, there is a built-in observer mode in Java. Observable (class) and observer (Interface) in Java. util ). But there are many disadvantages, such as violation: for the interface, instead of implementing programming and multi-purpose combination, less inheritance, and notesy also depends on the order.

Points of observer mode:

The observer defines the one-to-many relationship between objects.

The topic uses a common interface to update the observer.

The observer and the observer are loosely coupled. The observer does not know the details of the observer, but only knows that the observer implements the observer interface.

In this mode, you can push or pull data from an observer.

When multiple observers exist, they cannot depend on the specific notification order.

Pay attention to the problems caused by Java. util. Observable implementation.

If necessary, you can implement your own observable.

Application of observer Mode

Advantages of observer Mode

The observer and the observability are abstract coupling.

Built a complete set of trigger chains

Disadvantages of observer Mode

Multi-Level Trigger Efficiency

Notifications of messages in Java are executed sequentially by default. An observer is stuck, which affects the overall efficiency.

Scenarios of observer Mode

Split associated behavior scenarios

Multi-level event triggering scenarios

Cross-system message exchange scenarios

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.