Design pattern Learning-Observer mode (Observer pattern)

Source: Internet
Author: User

0. Preface

The observer pattern can be used in many places, especially as part of the MVC pattern, in MVC, the Model (M): Storing data, view (V): Displaying data. When the data in the model changes, the view is notified, which is a typical observer pattern.

1. Definition

Observer pattern: Defines a one-to-many relationship, an object as the subject, which maintains a series of dependent objects that, when the state of the subject changes, automatically notifies the dependent object (usually by invoking the method of the dependent object).

Official definition: wiki

2. Application

The Observer pattern is implemented here through the example in Head first design mode. There is a weather data and an announcement column, when the weather data changes, the announcement column will be notified to update the data.

Source:

Topic Subject Interface:

 1  package   Observerpattern;  2   Public  interface   Subject { 4  public  void   Registerobserver (Observer Observer);  5  public  void   Removeobserver (Observer Observer);  6  public  void   Notifyobservers ();  7 } 

Viewer Observer interface

1  Package Observerpattern; 2 3  Public Interface Observer {4      Public void update (Object obj); 5 }

Meteorological Data Realization:

1  PackageObserverpattern;2 3 Importjava.util.ArrayList;4 ImportJava.util.Iterator;5 6  Public classWeatherdataImplementsSubject {7 8     PrivateArraylist<observer> observers =NULL;9     Private Doubletemperature;Ten     Private Doublehumidity; One     Private Doublepressure; A      -      PublicWeatherdata () -     { theObservers =NewArraylist<>(); -     } -      -      Public Doublegettemperature () { +         returntemperature; -     } +  A      Public Doublegethumidity () { at         returnhumidity; -     } -  -      Public Doublegetpressure () { -         returnpressure; -     } in  -      Public voidSetweather (DoubleTemperature,DoubleHumidity,Doublepressure) to     { +          This. Temperature =temperature; -          This. Humidity =humidity; the          This. Pressure =pressure; * mesurementschanged (); $     }Panax Notoginseng      -      Public voidmesurementschanged () the     { + notifyobservers (); A     } the      + @Override -      Public voidregisterobserver (Observer Observer) { $ OBSERVERS.ADD (Observer); $     } -  - @Override the      Public voidremoveobserver (Observer Observer) { - OBSERVERS.REMOVE (Observer);Wuyi     } the  - @Override Wu      Public voidnotifyobservers () { -          About          for(Iterator<observer> Iterator =Observers.iterator (); Iterator.hasnext (); ) { $Observer Observer =(Observer) Iterator.next (); -Observer.update ( This); -         } -     } A  +}

Display interface:

1  Package Observerpattern; 2 3  Public Interface Displayboard {4      Public void display (); 5 }

Announcement Bar Implementation:

1  PackageObserverpattern;2 3  Public classCurrentweatherboardImplementsObserver, Displayboard {4 5     Private Doubletemperature;6     7      PublicCurrentweatherboard (Subject Subject) {8Subject.registerobserver ( This);9     }Ten      One @Override A      Public voidupdate (Object obj) { -         if(objinstanceofweatherdata) { -Weatherdata Weatherdata =(weatherdata) obj; the              This. Temperature =weatherdata.gettemperature (); - display (); -         } -     } +  - @Override +      Public voiddisplay () { ASystem.out.println ( This. GetClass (). GetName () + ":" + This. temperature); at     } -  -}

3. Observable class analysis in JDK

The observable class and the Observer interface are available in the JDK for easy implementation of the observer pattern, but the theme here is that observable is a class that needs to be implemented by inheritance, so it's a big limit to its use.

The addition of the observer method to the observable class, which is synchronized through the synchronized, maintains a vector container inside the observable that holds the Observer object.

 1  public  synchronized  void   Addobserver (Observer o) { 2  if  (o = = null  )  3  throw  new   NullPointerException ();  4   Obs.contains (o)) { 5   Obs.addelement (o ); 6   7
     } 

notification function, where an identity is judged, so call the Setchanged method before invoking the notification, and then save its observer to an array, there is a problem, that is, when the call deletes an observer, if Notifyobservers is being called, The deleted observer is still notified. The same is true for additions, which will miss this notification.

1  Public voidnotifyobservers (Object Arg) {2 3 object[] arrlocal;4 5         synchronized( This) {6             if(!changed)7                 return;8Arrlocal =Obs.toarray ();9 clearchanged ();Ten         } One  A          for(inti = arrlocal.length-1; i>=0; i--) -((Observer) arrlocal[i]). Update ( This, ARG); -}

Design pattern Learning-Observer mode (Observer 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.