The Observer object is the observer, and theobservable object is the observer.
Official website API Document: http://docs.oracle.com/javase/7/docs/api/
1.implementing the Observer patternThe implementation of the observer pattern is very simple, [1] creates the Observer class, which inherits from the Java.util.Observable class; [2] creates the Observer class, which implements the Java.util.Observer interface;
- For the class of the person being observed:
Add its observer: void Addobserver (Observer o) addobserver () method to add the Observer object to the list of observer objects
When an event in the observer changes, execute setchanged (); Notifyobservers (); the Setchange () method is used to set an internal flag bit indicating that the data has changed; Notifyobservers () Method calls the update () method of all observer in the Observer object list to notify them that the data has changed. Only after Setchange () is called, Notifyobservers () will call Update ().
- For the Observer class, the only way to implement the Observer interface update
void Update (Observable o, Object Arg)
The parameter, object arg, corresponds to an argument passed by Notifyobservers (object Arg), and when the notifyobservers () is executed, ARG is null.
Observed by: Servermanager
PackageCom.test.observer;Importjava.util.Observable; Public classServermanagerextendsObservable {Private intdata = 0; Public intGetData () {returndata; } Public voidSetData (inti) { if( This. data! = i) { This. data =i;setchanged ();} Notifyobservers (); //only after Setchange () is called, Notifyobservers () will call Update (), otherwise nothing is done. } } }}
Observer One: Aobserver
Importjava.util.Observable;ImportJava.util.Observer; Public classAobserverImplementsObserver { Publicaobserver (Servermanager sm) {Super(); //TODO auto-generated Constructor stubSm.addobserver ( This); Register to join the Observer} @Override Public voidUpdate (Observable arg0, Object arg1) {System.out.println ("Aobserver Receive:data have changed to" +( (Servermanager) arg0). GetData ()); }}
Observer II: Bobserver
Importjava.util.Observable;ImportJava.util.Observer; Public classBobserverImplementsObserver { Publicbobserver (Servermanager sm) {Super(); Sm.addobserver ( This); Register to join the Observer} @Override Public voidUpdate (Observable o, Object Arg) {//TODO auto-generated Method StubSystem.out.println ("Bobserver receive:data have changed to" +((Servermanager) O). GetData ()); }}
Test:
public class Testdemo { public static void main (string[] args) { /span>// TODO auto-generated method stub Se Rvermanager sm = new Servermanager (); Aobserver a = new Aobserver (SM); Bobserver b = new Bobserver (SM); Sm.setdata ( 5 10
Operation Result:
One, the Java comes with the Observer pattern