Observer mode in Java Design Mode

Source: Internet
Author: User

Observer mode in Java Design Mode

Abstract: ObserverPattern ). It is used to monitor the dynamics of some objects in real time. As long as the Object changes, all its Observer will know and then the Observer will perform the next operation based on the Object changes. This is the most common in SWING programming. The Listener is the observer.

I. Problem Introduction

To implement a weather forecast function, when the weather data changes, the weather will be displayed in real time in three forms: current weather conditions, statistical analysis, and weather forecast. There may be a fourth display.

Here, no matter how the data comes, we assume that we can get the data. In a program, the yyobserver method of the observed object is called to notify all observers.

Ii. Problem Analysis

1. Through analysis, we can draw a simple conclusion: Once the weather data is updated, it is necessary to change the display in real time. The observer mode can effectively solve this model problem.

2. To use the observer model, you must find out who is the observer and who is the observer. Here there is a simple principle. The relationship between the observer and the observer is many-to-one. relationship, that is, there is only one observer, that is, our weather data information, and the observer are three terminals that want to display different information (of course there can be a fourth observer ).

3. Because every observer must dynamically display information, we should abstract a class or interface for displaying information.

4. Since the division of roles is clear, the next step is design and assembly.

5. Considering scalability, low coupling, flexibility, and openness to expansion, modification and closure principles, and interface-oriented programming, We will design the specific classes below.

6. Based on the role, we can abstract three interfaces:

A) All observer interfaces -- Subject;

B) all Observer interfaces-Observer;

C) interface for displaying information -- DisplayElement;

7. For Subject, there are of course three methods for operating Observer, registering, removing, and notifying Observer (the Observer must be combined with the Observer ).

8. There must be an update method for the Observer, that is, once a change is detected in the Subject, the information will be updated, so the DisplayElement interface must be implemented.

II. Specific implementation

1. design the Subject interface:

package com.chy.dp.observer;public interface Subject {public void registerObserver(Observer observer);public void removeObserver(Observer observer);public void notifyObserver();}

2. design the Observer interface:

package com.chy.dp.observer;public interface Observer {public void update(float temp, float humidity, float pressure);}

3. Design the DisplayElement interface:

package com.chy.dp.observer;public interface DisplayElement {public void display();}

4. design the observed Subject interface-WeatherDate

Package com. chy. dp. observer; import java. util. arrayList; import java. util. list; public class WeatherDate implements Subject {// The Observer array can be used to explain why listprivate List is not required.
 
  
Observers = new ArrayList
  
   
(); Private float temperature; private float humidity; private float pressure; @ Overridepublic void registerObserver (Observer observer) {observers. add (observer) ;}@ Overridepublic void removeObserver (Observer observer) {int index = observers. indexOf (observer); if (index> = 0) {observers. remove (observer) ;}@overridepublic void policyobserver () {for (int I = 0; I <observers. size (); I ++) {Observer o = (Observer) observers. get (I); o. update (temperature, humidity, pressure) ;}/ *** automatically triggers the yyobserver function */public void measurementsChanged () {notifyObserver ();} /*** simulates data changes, that is, when we call this method, it indicates data changes, so that all observers will be notified */public void setMeasurements (float temperature, float humidity, float pressure) {this. temperature = temperature; this. humidity = humidity; this. pressure = pressure; measurementsChanged ();}}
  
 

5. The next step is to implement the specific implementation of our Observer -- CurrentConditionDisplay:

Package com. chy. dp. observer; public class CurrentConditionDisplay implements DisplayElement, Observer {private float temperature; private float humidity; private Subject weatherDate; /*** the observer passes in through the constructor and registers the observer to the Observer * this perfectly combines the observer with the Observer * @ param weatherDate */public currentConditionDisplay (Subject weatherDate) {super (); this. weatherDate = weatherDate; this. weatherDate. registerObserver (this) ;}@ Overridepublic void update (float temperature, float humidity, float pressure) {this. temperature = temperature; this. humidity = humidity; display () ;}@ Overridepublic void display () {System. out. println ("Current comditions:" + temperature + "F degrees and" + humidity + "% humidity ");}}


6. Similarly, the Code for displaying ForecastConditionDisplay and StatisticsDisplay is very similar to that above.

7. Client:

Package com. chy. dp. observer; @ SuppressWarnings ("unused") public class Client {public static void main (String [] args) {WeatherDate subject = new WeatherDate (); forecastConditionDisplay fcd = new ForecastConditionDisplay (subject); CurrentConditionDisplay ccd = new CurrentConditionDisplay (subject); // Changes the status of the observer, and the observer makes a display adjustment subject. setMeasurements (19, 40, 20 );}}


Iv. Summary and supplement

1. Summary:

The core of the observer mode is to first distinguish roles, locate the relationship between the observer and the observer, and the relationship between the observer and the observer. The key to implementation is to establish the relationship between the observer and the observer. For example, a set in the Observer class is used to store the observer. When the detected thing changes, it is necessary to notify all observer. In the constructor of the observer, You need to input the object to be observed to register yourself to the list held by the observer so that the observer can promptly notify the Observer of the State of the relationship. changes have been made and calls Methods common to the observer to pass the changes over.

2. Supplement:

There is nothing to add. The god of design patterns is that they are ultimately built on some of the most basic design principles. The ultimate goal is to make the architecture flexible, extensive, and strong. This is the only criterion for evaluating the quality of a project.

More: the beginning of the Java Design Pattern


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.