Design pattern Collation _ Observer mode

Source: Internet
Author: User

  The Observer pattern defines a one-to-many dependency between objects, so that when an object's state changes, all its dependents are notified and updated.

The object being observed is called the subject (Subject), and the object that observes the observed object is called the Observer (Observer).

Real-world observer patterns: for example newspaper subscriptions. Different people (Observer) order newspapers to the newspaper (Subject), and when a newspaper produces a new newspaper, it will inform its subscribers and deliver the newspaper. Subscribers can cancel their subscription, and the newspaper will no longer give him the newspaper. But as long as the newspaper has been there, , someone can subscribe to the newspaper.

In Javagui, there is the embodiment of the observer pattern, such as the implementation of button buttons. JButton will have ways to add and remove listener (listeners).

The Observer pattern provides an object design that allows for a loose coupling between the subject and the observer. On everything about the observer, the subject only knows that the observer implements an interface, and the subject does not need to know who the observer's implementation class is, what it does, or any other detail. At runtime, we can replace existing observers with new observers, The subject does not receive any impact. The new type of observer appears, and the subject does not need to be modified, just to implement the Observer interface in the new class, and then register as an observer. Changing either the subject or the observer does not affect the other party, since the two are loosely coupled and all are free to change.

Example:

  

Importjava.util.ArrayList;/** Demo theme. **/ Public InterfaceSubject { Public voidRegisterobserver (Observer o);//Registered Observer     Public voidRemoveobserver (Observer o);//removing observers     Public voidNotifyobservers ();//notifies the observer when the subject state has changed. }classWeatherdataImplementsSubject {PrivateArraylist<observer> observers;//The observer queue does not need to know the specific implementation details of the observer.     Private floattemperature; Private floathumidity; Private floatpressure;  PublicWeatherdata () {observers=NewArraylist<observer>(); } @Override Public voidregisterobserver (Observer o) {observers.add (o); System.out.println ("Register an Observer."); } @Override Public voidremoveobserver (Observer o) {intI=Observers.indexof (o); if(i>=0) Observers.remove (o); System.out.println ("Remove an observer."); } @Override Public voidnotifyobservers () { for(inti = 0; I < observers.size (); i++) {            /** This is because each observer implements the observer interface, so we know how to notify the observer to make the update action. * */Observers.get (i). Update (temperature, humidity, pressure); }    }         Public voidMeasurementschanged ()/*when the state changes, you need to notify the Observer*/{notifyobservers (); }         Public voidSetmeasurements (floatTemperature,floatHumidity,floatpressure) {         This. temperature=temperature;  This. humidity=humidity;  This. pressure=pressure;    Measurementschanged (); }}
/** Demo Viewer **/ Public InterfaceObserver { Public voidUpdatefloatTempfloatHumidity,floatpressure);}classCurrentconditionobserverImplementsObserver/*The Observer interface is implemented, and changes can be obtained. */ {    Private floattemperature; Private floathumidity; PrivateSubject Weatherdata;  Publiccurrentconditionobserver (Subject weatherdata) { This. Weatherdata = Weatherdata;//The constructor requires the Weatherdata object to be used as a registration. Weatherdata.registerobserver ( This); } @Override Public voidUpdatefloatTempfloatHumidity,floatpressure) {         This. temperature=temp;  This. humidity=humidity;    Display (); }     Public voiddisplay () {System.out.println ("Current Conditions:" +temperature+ "F degrees and" +humidity+ "% humidity"); }    }
/** test subjects and observers. Only one observer is used here.*/ Public classTest { Public Static voidMain (string[] args) {Weatherdata data=NewWeatherdata (); Currentconditionobserver Obs=Newcurrentconditionobserver (data); Data.setmeasurements (80, 65, 30); Data.setmeasurements (29.2f, the); Data.setmeasurements (0, 29.2f);    Data.removeobserver (OBS); }}

The class diagram is as follows:

  

Design pattern Collation _ 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.