Sample observer mode in Java

Source: Internet
Author: User
The observer mode is a mature mode for multiple objects to know data changes in an object. In the observer mode, there is an object called "theme" and several objects called "Observer". The relationship between "theme" and "Observer" is a one-to-many dependency.

. When the status of the "topic" changes, all "observers" are notified.

Advantages of observer mode:
The relationship between a specific topic and a specific interface is relaxed. Because the topic interface only depends on the observer interface, the actual topic only knows that its observer is an instance that implements the observer interface, however, you do not need to know the specific class. Similarly, the melancholy observer

Only depends on the topic interface. Therefore, a specific observer only knows that the topic it depends on is an instance of a class that implements the topic interface, but does not need to know which class it is.

The observation mode satisfies the "On-Off principle" topic interface and only relies on the observer interface. In this way, the class that creates a specific topic is only dependent on the observer interface. Therefore, if you add a new class that implements the observer interface, you do not have to modify the class that creates a specific topic.

. Similarly, the class for creating a specific observer only depends on the topic interface. If a new class for implementing the topic interface is added, you do not need to modify the code for creating a specific observer.

Example:
Mr. Li hopes to know the weather forecast of the weather station and daily travel information of the travel agency in time.

Mr. Li is a specific observer, and meteorological stations and travel agencies have become the topic.

1. The topic interface specifies how to add, delete, and notify the observer to update data for a specific topic.

Package Org. zhy. observer. demo02.subject; import Org. zhy. observer. demo02.observer. observer;/*** subject * @ author Zhengyi **/public interface subject {public void addobserver (Observer O); // Add the observer public void delobserver (Observer O ); // remove the observer public void notfilyobserver ();}

2. The observer interface specifies the methods used by the observer to update data.

Package Org. zhy. observer. demo02.observer; import Org. zhy. observer. demo02.subject. subject;/*** Observer * @ author Zhengyi **/public interface observer {public void Update (subject );}

3. Specific theme-Meteorological Station

Package Org. zhy. observer. demo02.subject. impl; import Java. util. arraylist; import Org. zhy. observer. demo02.observer. observer; import Org. zhy. observer. demo02.subject. subject;/*** subject ** @ author Zhengyi **/public class weatherstation implements subject {string forecasttime, forecasponess; int maxtemperature, mintemperature; arraylist <observer> personlist; public weatherstation () {personlist = new arraylis T <observer> () ;}@ overridepublic void addobserver (Observer O) {If (o! = NULL )&&(! Personlist. Contains (O) {personlist. Add (o) ;}@ overridepublic void delobserver (Observer O) {If (o! = NULL) {personlist. remove (o) ;}/// notify all observers @ overridepublic void notfilyobserver () {for (INT I = 0; I <personlist. size (); I ++) {observer o = personlist. get (I); O. update (this) ;}}/*** new message ** @ Param T * @ Param mess * @ Param Max * @ Param min */Public void doforecast (string t, string mess, int Max, int min) {This. forecasttime = T; this. forecasponess = mess; this. maxtemperature = max; this. mintemperature = min; notfilyobserver (); // call the notification observer function if a new message exists} Public String getforecasttime () {return forecasttime;} Public String getforecasponess () {return forecasponess;} public int getmaxtemperature () {return maxtemperature;} public int getmintemperature () {return mintemperature ;}}

4. Specific theme-Travel Agency

package org.zhy.observer.demo02.subject.impl;import java.util.ArrayList;import org.zhy.observer.demo02.observer.Observer;import org.zhy.observer.demo02.subject.Subject;public class TravelAgency implements Subject {String tourStartTime;String tourMess;ArrayList<Observer> personList;public TravelAgency() {personList = new ArrayList<Observer>();}@Overridepublic void addObserver(Observer o) {if ((o != null) && (!personList.contains(o))) {personList.add(o);}}@Overridepublic void delObserver(Observer o) {if (o != null) {personList.remove(o);}}@Overridepublic void notfilyObserver() {for (int i = 0; i < personList.size(); i++) {Observer o = personList.get(i);o.update(this);}}public void giveMess(String time, String mess) {this.tourMess = mess;this.tourStartTime = time;notfilyObserver();}public String getTourMess() {return tourMess;}public String getTourStartTime() {return tourStartTime;}}
5. Specific observer-Mr. Zhang
Package Org. zhy. observer. demo02.observer. impl; import Org. zhy. observer. demo02.observer. observer; import Org. zhy. observer. demo02.subject. subject; import Org. zhy. observer. demo02.subject. impl. travelagency; import Org. zhy. observer. demo02.subject. impl. weatherstation; public class person implements observer {subject travelsubject, weathersubject; string values, forecasponess; int maxtemp, mintemp; string tourstarttime, tourmess; Public Person (subject travelsubject, subject weathersubject) {This. travelsubject = travelsubject; this. weathersubject = weathersubject; travelsubject. addobserver (this); weathersubject. addobserver (this) ;}@ overridepublic void Update (subject) {If (subject instanceof weatherstation) {weatherstation we = (weatherstation) subject; forecasponess = We. getforecasponess (); forecatstime = We. getforecasttime (); maxtemp = We. getmaxtemperature (); mintemp = We. getmintemperature (); system. out. println ("Weather Forecast:" + forecatstime + "," + ", weather condition:" + forecastmess + ", maximum temperature:" + maxtemp + ", minimum Temperature "+ mintemp);} else if (subject instanceof travelagency) {travelagency TR = (travelagency) subject; tourmess = tr. gettourmess (); tourstarttime = tr. gettourstarttime (); system. out. println ("Tourism start date:" + tourstarttime + ", tourism information:" + tourmess );}}}
6. program call
Package Org. zhy. observer. demo02; import Org. zhy. observer. demo02.observer. impl. person; import Org. zhy. observer. demo02.subject. impl. travelagency; import Org. zhy. observer. demo02.subject. impl. weatherstation; public class appliction {public static void main (string [] ARGs) {weatherstation we = new weatherstation (); travelagency TA = new travelagency (); person mrli = new person (TA, We); we. doforecast ("10", "overcast with light rain", 28, 20); TA. givemess ("10", "Huangshan two-day tour"); we. doforecast ("11", "Qing", 30, 15); TA. givemess ("11", "Huashan one-day tour ");}}

Running result:

Suitable for scenarios in the Observer Mode
1. When the data of an object is updated, other objects need to be notified, but this object does not want to be notified to form a tightly coupled object.
2. When the data of an object is updated, this object requires other objects to update their own data, but this object does not know how many objects need to update data.

Related Article

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.