"Design pattern" Headfirst design pattern (II): Observer (Observer) mode

Source: Internet
Author: User

One, the Observer pattern definition

In the Observer pattern, an observer manages the observer object that relies on it, and it defines a one-to-many dependency, so that when an object changes state, all its dependents are notified and updated automatically.

The subject (The observer) updates the observer through a common interface, and the observer relies on this topic.

II. Observer Model example--meteorological monitoring system

Describe:

The meteorological monitoring system is divided into three parts: Weather stations (physical devices that obtain actual meteorological data), Weatherdata objects (tracking data from weather stations and updating bulletin boards) and bulletin boards (showing the current weather conditions to the user)

The bulletin board is divided into three : current status (showing Weatherdata current observations), meteorological statistics (showing minimum, average and maximum observations), Weather forecast (weather forecast according to barometer)

Target :

Automatically update three bulletin boards when the Weatherdata object changes

Implementation :

First, let's take a look at the source file for the Weatherdata class:


Gettemperature (), gethumidity (), Getpressure () three methods for obtaining temperature, humidity, air pressure

Measurementschanged (): Once the measurement is updated, this method is called (No need to care about how it is called)

We then add the code inside the Measurementschanged () method:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >public void measurementschanged () {Float temp = gettemperature (); Float humidity = gethumidity (); Float pressure = GETPR Essure ();//updated three bulletin board currentconditionsdisplay.update (temp,humidity,pressure) in this three method; Statisticsdisplay.update ( Temp,humidity,pressure); forecastdisplay.update (temp,humidity,pressure);} </span>
as we can see, the top three methods are like a unified interface and are changed and programmed for specific implementations , which will cause the program to be modified later when the bulletin board is added or removed


Here, a concept is introduced- loosely coupled : When two objects are loosely coupled, they can still interact, but are less aware of each other's details.

The Observer pattern provides an object design that allows for loose coupling between the subject and the Observer:

The topic needs only to know that the observer implements an interface (Observer interface), that the subject does not need to know who the observer is, what it does, or any other detail.

Can draw out the class diagram:


A topic can have a lot of observers (they are a combination of relationships, which are described below), in which the following methods are in the topic:

Registerobserver (): Registering the viewer for the subject

Removeobserver (): Remove the subject's viewer

Notifyobserver (): Notify the viewer

The Observer has a method:

Update (): Updates based on notifications


Below, the class diagram of the weather station is designed and implemented specifically:


Subject interface: A method for registering, removing, notifying observers

Weatherdata class, inheriting the subject interface:

(1) Properties: List of observers, temperature, humidity, air pressure

(2) Method: Register, remove, notify the Observer, obtain temperature, humidity, air pressure and notify the observer when the status changes

Observer interface: With Update method

Displayment interface: The consent interface established for the bulletin board, which only needs to implement the Display method

Currentconditionsdisplay class: Displays the current observations based on the Weatherdata object

Statisticsdisplay class: Displays the minimum, average, and maximum observed values

The following code is used to implement the specific:

Subject interface:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >public interface Subject {void Registerobserver (Observer o); void Removeobserver (Observer o); void Notifyobservers () ;} </span>
Weatherdata class:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >public class Weatherdata implements Subject {//Add observer private arraylist<observer> observers;private float temperature;private float humidity;private float pressure;public weatherdata () {observers = new Arraylist<observer > ();} public void Registerobserver (Observer o) {observers.add (o);} public void Removeobserver (Observer o) {int i = Observers.indexof (o); if (i >= 0) {observers.remove (i);}} public void Notifyobservers () {for (int i = 0; i < observers.size (); i++) {Observer Observer = (Observer) observers.get (i); observer.update (temperature, humidity, pressure);}} Notifies the Observer public void measurementschanged () {notifyobservers () when the state changes;} Update weather data public void setmeasurements (float temperature, float humidity,float pressure) {this.temperature = temperature;this.humidity = Humidity;this.pressure = Pressure;measurementschanged ();} public float gettemperature () {return temperature;} public float gethumidity () {return humidity;}public float getpressure () {return pressure;}} </span>
Observer Interface:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >public interface Observer {void update (float temp,float humidity, float pressure);} </span>
Displayment Interface:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >public interface Displayelement {void display ();} </span>
Currentconditionsdisplay class:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >public class Currentconditionsdisplay implements Observer, displayelement {private float temperature;private float HUMIDITY;//Register as Observer public Currentconditionsdisplay (Subject weatherdata) {weatherdata.registerobserver (this) when initializing ;} public void update (float temperature, float humidity, float pressure) {this.temperature = Temperature;this.humidity = Humi Dity;display ();} public void display () {System.out.println ("Current conditions:" + temperature+ "F degrees and" + humidity + "% humidity" );}} </span>
Statisticsdisplay class: Displays the minimum, average, and maximum observed values

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;"  >public class Statisticsdisplay implements Observer, displayelement {private float maxtemp = 0.0f;private float mintemp = 200;private float tempsum = 0.0f;private int numreadings;//initialized when registered as observer public Statisticsdisplay (Weatherdata Weatherdata) {weatherdata.registerobserver (this);} public void update (float temp, float humidity, float pressure) {tempsum + temp;numreadings++;if (Temp > maxtemp) {maxt EMP = temp;} if (Temp < mintemp) {mintemp = temp;} Display ();} public void display () {System.out.println ("avg/max/min temperature =" + (tempsum/numreadings) + "/" + Maxtemp + "/" + mi ntemp);}} </span>
Write a main function below to verify:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >public class Weatherstation {public static void main (string[] args) {Weatherdata weatherdata = new Weatherdata (); Currentconditionsdisplay cu = new Currentconditionsdisplay (weatherdata); Statisticsdisplay st = new Statisticsdisplay (weatherdata); weatherdata.setmeasurements (30.4f); System.out.println ("======================"); weatherdata.setmeasurements (29.2f); System.out.println ("======================"); weatherdata.setmeasurements (29.2f); System.out.println ("======================");//Lower STATISTICSDISPLAY this observer removed Weatherdata.removeobserver (ST); Weatherdata.setmeasurements (35.5f);}} </span>
Output:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >current conditions:80.0f degrees and 65.0% humidityavg/max/min temperature = 80.0/80.0/80.0====================== Current conditions:82.0f degrees and 70.0% humidityavg/max/min temperature = 81.0/82.0/80.0====================== Current conditions:78.0f degrees and 90.0% humidityavg/max/min temperature = 80.0/82.0/78.0====================== Current conditions:90.0f degrees and 70.0% humidity</span>




"Design pattern" Headfirst design pattern (II): Observer (Observer) mode

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.