For the observer pattern, Java has already provided us with existing interfaces and classes. For subscribers (SUBSCRIBE, observer) Java provides an interface for us, the JDK source code is as follows:
1 Package Java.util; 2 3 Public Interface Observer {4 void Update (Observable o, Object arg); 5 }
Just like our last observer of the implementation, we only provide an update method for notifying the notified person of the notification to make the corresponding change.
Let's look at Java to provide us with a kind of notice (Publish, publisher), the JDK source code is as follows:
1 PackageJava.util;2 3 Public classObservable {4 Private BooleanChanged =false; Whether to change the state5 PrivateVector Obs; Vector is thread-safe with synchronous methods, and thread safety does not cause data confusion in multithreaded situations6 7 PublicObservable () {8OBS =NewVector ();9 }Ten One Public synchronized voidaddobserver (Observer o) { A if(O = =NULL) - Throw Newnullpointerexception (); - if(!obs.contains (o)) { the obs.addelement (o); - } - } - + Public synchronized voiddeleteobserver (Observer o) { - obs.removeelement (o); + } A at Public voidnotifyobservers () { -Notifyobservers (NULL); - } - - Public voidnotifyobservers (Object Arg) { - object[] arrlocal; in - synchronized( This) { to if(!changed)//the status value is not changed when returned without notification + return; -Arrlocal =Obs.toarray (); Convert vectors to an array the clearchanged (); Reset Status * } $ Panax Notoginseng for(inti = arrlocal.length-1; i>=0; i--) -((Observer) arrlocal[i]). Update ( This, ARG); the } + A Public synchronized voiddeleteobservers () { the obs.removeallelements (); + } - $ protected synchronized voidsetchanged () { $Changed =true; - } - the protected synchronized voidclearchanged () { -Changed =false;Wuyi } the - Public synchronized BooleanhasChanged () { Wu returnchanged; - } About $ Public synchronized intcountobservers () { - returnobs.size (); - } -}
I have to say that Java source code is better than its own writing. First, it is thread-safe to use vector,vector compared to ArrayList. Second, the Synchronized keyword is used for two methods when adding and removing observers, which is considered for multithreading. It is true that Java source code is not so scary, it is also a combination of some of the simplest and most basic.
Let's take a look at how to implement the observer pattern using the interfaces and methods provided by Java.
1 Packageday_10_observer_jdk;2 3 Importjava.util.Observable;4 ImportJava.util.Observer;5 6 /**7 * Observers that implement the Java.util.Observer interface8 * @authorTurbo9 *Ten * September 14, 2016 One */ A Public classSubscribeImplementsObserver { - - PublicSubscribe (Observable o) { theO.addobserver ( This);//put the observer in the observer to be notified - } - /*(Non-javadoc) - * @see java.util.observer#update (java.util.Observable, Java.lang.Object) + */ - @Override + Public voidUpdate (Observable o, Object Arg) { ASYSTEM.OUT.PRINTLN ("Notification Received:" +((Publish) O). GetData ()); at } - -}
1 Packageday_10_observer_jdk;2 3 Importjava.util.Observable;4 5 /**6 * successor to Java.util.Observable's notifier7 * @authorTurbo8 *9 * September 14, 2016Ten */ One Public classPublishextendsObservable { A PrivateString data = ""; - - PublicString GetData () { the returndata; - } - - Public voidsetData (String data) { + if(! This. Data.equals (data)) { - This. data =data; +Setchanged ();//Change the status of a notifier A } atNotifyobservers ();//Call the Parent class observable method to notify all observers - } -}
Client Test Code:
1 Packageday_10_observer_jdk;2 3 /**4 * @authorTurbo5 *6 * September 14, 20167 */8 Public classMain {9 Ten /** One * @paramargs A */ - Public Static voidMain (string[] args) { -Publish Publish =NewPublish (); theSubscribe Subscribe =NewSubscribe (publish); - -Publish.setdata ("Start"); - } + -}
This allows us to take advantage of the Observer interface and the observable class provided by Java to implement the Observer pattern. In the previous article we referred to the event delegate, and in the next article we will look at what is the event delegate.
Implement observer patterns with Java-provided observer interfaces and observable classes