Java, as an object-oriented development language, provides good support for implementation and design patterns and provides many default implementations, such: the observable class and observer interface in Java can be used to conveniently implement the observer mode.
Next we will use a practical example to illustrate: in daily life, the most common example of an observer is the weather forecast. Here we observe the earth, however, we detect meteorological changes on the earth by launching the Meteorological Satellite observer.
Therefore, this example involves three objects:
Earth: observed object
Satellite: Observer
Weather Service: client call
Observed object: Earth)
Import java. util. observable;
/***//**
* Observed object: Earth
*
* @ Author zjun
* @ Version 1.0 create on 9:42:45
*/
Public class Earth extends observable {
Private string weather = "Sunny ";
/***//**
* @ Return returns the weather.
*/
Public String getweather (){
Return weather;
}
/***//**
* @ Param weather
* The weather to set.
*/
Public void setweather (string weather ){
This. Weather = weather;
// Set the Change Point
Setchanged ();
Notifyobservers (weather );
}
}
[Note] Before detecting an object, you must set the change point setchanged () and notify the observer yyobservers (). These two functions are implemented by the observable class, encapsulates the implementation details of the observer mode.
Observer: Satellite)
Import java. util. observable;
Import java. util. observer;
/***//**
* Observed object: Meteorological Satellite
*
* @ Author zjun
* @ Version 1.0 create on 9:46:30
*/
Public class satellite implements observer {
Private string weather;
Public void Update (observable OBJ, object Arg ){
Weather = (string) ARG;
// Capture weather changes and report them to the tester
System. Out. println ("recent weather changes:" + weather );
}
}
Client call: Weather Service)
/***//**
* Client call: Weather Forecast
*
* @ Author zjun
* @ Version 1.0 create on 9:57:19
*/
Public class weatherservice {
/***//**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Earth = New Earth ();
Satellite = new satellite ();
// Launch a meteorological satellite
Earth. addobserver (satellite );
System. Out. println ("Weather Forecast :");
System. Out. println ("------------");
Earth. setweather ("Typhoon 'Pearl 'approaching ");
Earth. setweather ("rainstorm ");
Earth. setweather ("Hot Weather ");
}
}
[Running result]
Weather Forecast:
------------
Recent weather changes: typhoon 'Pearl 'approaching
Recent weather changes: heavy rain
Recent weather changes: hot weather
Note: I am not liable for any of the above content from the Internet.
This article from: http://www.javatx.cn/clubPage.jsp? Ccstyle = 0 & tid = 632 & CCID = 14