(Java) Zero-based-observer design pattern Observer

Source: Internet
Author: User

Observer design pattern: When a specified action occurs on an object, it is processed by another object.

Steps:
1. A The specified action of a object occurs is, to notify B,c,d ... object to make the corresponding processing, this time should put b,c,d ... The corresponding processing method of an object's action on a object is defined on the interface (this is a specification, the object that needs to be notified by a object, all of which implements the interface).
2. In the A object maintains a reference to the interface, the method in the interface can be called when a specified action occurs on the A object.

Application scenarios for observer patterns:

1. Updates to an object state require other objects to be updated synchronously, and the number of other objects is dynamically variable.

2. Objects only need to notify their own updates to other objects without needing to know the details of other objects.

Suppose there is an example:

Weather forecasts are updated daily by the Meteorological Observatory, and the people who subscribe can receive weather forecasts at each meteorological observatory. Subscribers can deal with the weather forecast information

Observed objects (Subject)

1 /*2 * Meteorological Observatory class3  * 4  */5  Public classweatherstation {6 7     PrivateString[] Weatherarr = {"Heavy rain", "Heavy snow", "Typhoon", "Haze", "Cloudy", "Sunny"};8     PrivateString Weatherdesc = weatherarr[0];9     Privatearraylist<iweather> list =NewArraylist<iweather>();Ten      One     //provides a way for you to notify an object when adding a weather forecast update A      Public voidAdd (Iweather weather) { -          This. List.add (weather); -     } the      -     //provide a way to unsubscribe from the weather forecast -      Public voidRemove (Iweather weather) { -         if(weatherarr.length>0){ +              for(inti = 0; i < weatherarr.length; i++) { -                 if(List.get (i). Equals (Weather)) { +                      This. List.remove (i); A                      Break; at                 } -             } -              -         } -     } -      in      -     //Start Weather Forecast to      Public voidStartweatherforecast () { +         NewThread () { - @Override the              Public voidrun () { *                  while(true){ $Updateweather ();//weather forecast updated every 3 seconds (simulated daily meteorological station automatically updated weather forecast)Panax Notoginseng                      for(Iweather weather:list) { - Weather.updateweather (WEATHERDESC); the                     } +                     Try { AThread.Sleep (3000); the}Catch(interruptedexception e) { + e.printstacktrace (); -                     } $                      $                 } -             } - }.start (); the          -     }Wuyi      the      -     //Meteorological Observatory updates the weather Wu      Public voidUpdateweather () { -Random random =NewRandom (); About         intn =Random.nextint (weatherarr.length); $          This. Weatherdesc =Weatherarr[n]; -SYSTEM.OUT.PRINTLN ("Meteorological Observatory publishes weather forecast:" + This. Weatherdesc); -     } -      A}

All subscribed groups must have a common Updateweather method (implementing the interface) so that when the weather station publishes a new forecast, the method can be executed by invoking the subscription object to achieve the notification purpose.

/**/Publicinterface     iweather {publicvoid  updateweather (String weatherdesc);}

Subscribe to the group Class Watcher object Observer

1 /*2 * May subscribe to one of the group of Workers3  * 4  */5  Public classEmpImplementsIweather {6 7 String name;8     intAge ;9     Ten      PublicEMP (String name,intAge ) { One          This. Name =name; A          This. Age =Age ; -     } -  the     //{"Heavy rain", "Heavy snow", "Typhoon", "Haze", "Cloudy", "Sunny"} - @Override -      Public voidUpdateweather (String weatherdesc) { -System.out.println ( This. name+ ": Receive weather forecast" +weatherdesc); +     } -}

-

/** One of the possible subscribing groups, students*/ Public classStudentImplementsiweather {String name; intAge ;  PublicStudent (String name,intAge ) {         This. Name =name;  This. Age =Age ; }    //{"Heavy rain", "Heavy snow", "Typhoon", "Haze", "Cloudy", "Sunny"}@Override Public voidUpdateweather (String weatherdesc) {System.out.println ( This. name+ ": Receive weather forecast" +Weatherdesc); }}

Main,

1  Public classWeathermain {2 3      Public Static voidMain (string[] args) {4Weatherstation weatherstation =Newweatherstation ();5 6Student S1 =NewStudent ("Xiao Ming", 10);7Student s2 =NewStudent ("Mei", 10);8EMP e1 =NewEMP ("Daming", 10);9EMP e2 =NewEMP ("Great Beauty", 10);Ten Weatherstation.add (S1); One weatherstation.add (S2); A Weatherstation.add (E1); - Weatherstation.add (E2); - Weatherstation.remove (E2); the weatherstation.startweatherforecast (); -     } -  -}

Because "Big beautiful" canceled the weather forecast, so did not receive the weather forecast notice

Execution Result:

Meteorological Observatory publishes weather forecast: Heavy snow
Xiao Ming: Received the weather forecast snow
Amy: Received the weather forecast snow
Daming: Get the weather forecast snow
Meteorological Observatory publishes weather forecast: Fog Haze
Xiao Ming: Received the weather forecast fog haze
Amy: Received the weather forecast fog haze
Daming: Get weather forecast fog haze
Meteorological Observatory publishes weather forecast: Typhoon
Xiao Ming: Received the weather forecast typhoon
Amy: Received the weather forecast typhoon
Daming: Get weather forecast typhoon
Meteorological Observatory publishes weather forecast: Sunny
Xiao Ming: Receive the weather forecast fine
Amy: It's sunny to receive the weather
Daming: It's sunny to receive the weather
Meteorological Observatory publishes weather forecast: Fog Haze
Xiao Ming: Received the weather forecast fog haze
Amy: Received the weather forecast fog haze
Daming: Get weather forecast fog haze

...

(Java) Zero-based-observer design pattern Observer

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.