The Observer pattern is implemented in Java through the observable class and the Observer interface. The object that implements the observer interface is the observer, and the object that inherits the observable is the observer.
1.
implementing the Observer patternImplementing the Observer pattern is very simple, [1] creates the Observer class, which inherits from the Java.util.Observable class, [2] creates the Observer class, it implements the Java.util.Observer interface, and [3] for the Observer class, adds its observer:
void Addobserver (Observer o) |
The Addobserver () method adds the Observer object to the list of observer objects. When the observed event occurs, execute:
Setchanged (); Notifyobservers (); |
The Setchanged () method is used to set an internal flag bit indicating that the data has changed, and the 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 (). [4] 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. A simple example is given below:
PackageDesignpattern_observer;Importjava.util.Observable; Public classMybuttonobserableextendsObservable {PrivateString Clickmode; PublicString Getclickmode () {returnClickmode; } Public voidSetclickmode (String clickmode) { This. Clickmode =Clickmode; this.setchanged (); this . Notifyobservers (Clickmode); }}
Package Designpattern_observer; Import java.util.Observable; Import Java.util.Observer; Public class Implements Observer { @Override publicvoid update (Observable o, Object Arg) { if (arg.tostring (). Equals ("Double clicked")) { System.out.println (" You performed a double-click on the button. ); } }}
Test class:
Package Designpattern_observer; Public class observertest { publicstaticvoid main (string[] args) { New mybuttonobserable (); New mytextboxabserver (); Button.addobserver (textbox); Button.setclickmode ("double clicked");} }
Execute the entry function, call Button.setclickmode ("double clicked"), trigger the Update method of the Mytextboxabserver object, print out:
You perform a double-click operation on the button.
Using the Observer interface and observable class practices in Java Observer observer patterns