The Java built-in Observer pattern is the implementation of several main functions of the observer pattern by inheriting the parent class:
Observerable (observable): is a parent class (class), Addobserver (), adding observers; Deleteobserver (), delete observer;
Notifyobservers (), notify the Observer, Setchanged (), confirm the change;
OBSERVER (Observer): Is an interface (interface), update (), updating the observer data;
Setchanged ()->notifyobservers (), you must first use setchanged (), and then use Notifyobservers (), that is, to confirm the submission, and then notify the Observer;
The Observer's update Interface update (observerable o, Object Arg), that is, you can use push or pull (pull);
If Notifyobservers (ARG), passing the argument, the push (push) method, if there is no argument, is the way to pull (pull), that is, by using the Get () method;
The notice (notify) Order of the Observer is the first in and out mode.
Observerable (observable) code:
/**
* @time May 22, 2014 * * *
package Observer.java;
Import java.util.Observable;
/**
* @author C.l.wang * */Public
class Weatherdata extends observable {
private float temperature;
private float humidity;
private float pressure;
Public Weatherdata () {} public
void Measurementschanged () {
setchanged ();
Notifyobservers ();
}
public void setmeasurements (float temperature, float humidity, float pressure) {
this.temperature = temperature;< c20/>this.humidity = humidity;
This.pressure = pressure;
Measurementschanged ();
}
public float gettemperature () {return
temperature;
}
public float gethumidity () {return
humidity;
}
public float getpressure () {return
pressure
}}
OBSERVER (Observer) code:
/** * @time May 22, 2014 * * * Package Observer.java;
Import java.util.Observable;
Import Java.util.Observer;
/** * @author C.l.wang * */public class Currentconditionsdisplay implements Observer, Displayelement {
Observable observable;
private float temperature;
private float humidity;
Public Currentconditionsdisplay (observable observable) {this.observable = observable;
Observable.addobserver (this); }/* (non-javadoc) * @see observer.java.displayelement#display () * * * @Override Pub LIC void display () {//TODO auto-generated Method Stub System.out.println ("Current Conditions:" + te
Mperature + "F degrees and" + humidity + "% humidity");
}/* (non-javadoc) * @see java.util.observer#update (java.util.Observable, java.lang.Object) * * @Override public void update (observable o, objeCT arg) {//TODO auto-generated method stub if (o instanceof weatherdata) {Weatherdata
Weatherdata = (weatherdata) o;
This.temperature = Weatherdata.gettemperature ();
This.humidity = Weatherdata.gethumidity ();
Display (); }
}
}
This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/project/