Defines a one-to-many dependency between objects, so that when an object changes, all its dependents are notified and updated automatically.
The observer is to inherit: observable class implements message push, setchanged notifyobservers ();
The observer wants to inherit: The Observer class implements Updata (); Registered
Package watcher mode; import Java.util.observable;import java.util.Observer;/** * * * @author the RED DREAM * Observer mode: one-to-many mode * when the observer changes, the Observer is notified of the automatic Update * service is observed: Push message to notify the OBSERVER * Observer: Subscribe to topic Automatic Update message*/ Public classtest{ Public Static voidMain (string[] args) {Service s=NewService ();//Create a Watcher service personObserverl o =NewObserverl ();//Create observerObserverl O1 =NewObserverl ();//Create observerObserverl O2 =NewObserverl ();//Create observerObserverl O3 =NewObserverl ();//Create observerObserverl O4 =NewObserverl ();//Create observerO.registerservice (s);//Subscription ServicesO1.registerservice (s); O2.registerservice (s); O3.registerservice (s); O4.registerservice (s); //Cancel SubscriptionO1.unregisterservice (s); S.setmsg ("today's News hot"); }}/** * Service class is used by observers to push messages*/classService extends observable{PrivateString msg; PublicString getmsg () {returnmsg+"(from the service person (the observed person))"; } /** * * push message*/ Public voidsetmsg (String msg) { This. msg =msg; Setchanged ();//Setting ChangesNotifyobservers ();//notify the viewer } }
/**
* The class of the person being observed
*/classObserverl implements observer{/** * subscription service **/ Public voidRegisterservice (Observable Observable) {observable.addobserver ( This); } /** * Unsubscribe*/ Public voidUnregisterservice (Observable Observable) {observable.deleteobserver ( This); } /** * Implement the Observer's Update method*/@Override Public voidUpdate (Observable arg0, Object arg1) {if(arg0 instanceof Service) {service S=(Service) arg0; System. out. println ("Viewer Update:"+s.getmsg ()); } } }
Execution Result:
Observer UPDATE: Today's news hotspot (from the Service (Observer)) Observer update: Today's news hotspot (from the service Person (Observer)) Observer update: Today's news hotspot (from the service Person (Observer)) Observer update: Today's news hotspot (from the service person (The observer))
Java Watcher pattern