In the Java language Java.util Library, a observable class and a observer interface are provided, which form the Java language support for the Observer pattern.
The following is a direct look at how to use Java for observer mode support:
In the following example, the object of the observer is called watched, which is monitored, while the Observer object is called Watcher, which is the meaning of the watcher.
The watched object inherits from the observable class, and the Watcher object implements the Observer interface.
/** * is monitored object */public class watched extends observable{ private String data= ""; /* * Value Method * * /public String retrievedata () { return data; } /* * Change Method * * */public void Changedata (String data) { if (!this.data.equals (data)) { This.data=data; Setchanged (); } Notifyobservers (); }
/** * Monitors */public class Watcher implements observer{public watcher (watched W) { w.addobserver (this); } @Override public void update (Observable o, Object Arg) { System.out.println ("Data have been changed to: '" + (( Watched) O). Retrievedata () + "'"); }}
public class tester{ private static watched watched; private static Observer watcher; public static void Main (string[] args) { watched=new watched (); Watcher=new Watcher (watched); Watched.changedata ("1"); Watched.changedata ("1"); Watched.changedata ("2"); Watched.changedata ("3");} }
Java support for observer patterns