Observer Pattern--java Design pattern

Source: Internet
Author: User

Observer pattern Definition: defines a one-to-many dependency between objects, so that when an object changes state, all its dependents are notified and updated automatically. References such as:

The observer design pattern is also called the Publish-subscribe pattern.
It can also be called: Publisher + Subscriber = Observer mode
Examples of observer patterns in Android are: Broadcast mechanism, Contentobserver registration method, a synchronous observer pattern, and an asynchronous observer pattern.

When two objects are loosely coupled, they can still interact, but the details of each other are not clear, and the observer provides an object design that reduces the coupling between the two objects and avoids the bidirectional dependency of the object.
For example: Many of the listener in Android are observer patterns, such as the Onclicklistener of a click event, to avoid two-way dependency of the object.

--First look at the Observer pattern in the Java source Code: Observer Observer Interface:
package com.daming.java.observer;publicinterface Observer {    void update(Observable observable, Object arg);}
Implementation of the Object observable class
 PackageCom.daming.java.observer;ImportJava.util.Vector; Public  class Observable {    Private BooleanChanged =false;PrivateVector Obs; Public Observable() {Obs =NewVector (); } Public synchronized void Addobserver(Observer o) {if(O = =NULL)Throw NewNullPointerException ();if(!obs.contains (O))        {obs.addelement (o); }    } Public synchronized void Deleteobserver(Observer o)    {obs.removeelement (o); } Public void notifyobservers() {Notifyobservers (NULL); } Public void notifyobservers(Object Arg) {object[] arrlocal;synchronized( This) {if(!changed)return;            arrlocal = Obs.toarray ();        Clearchanged (); } for(inti = arrlocal.length-1; I >=0; i--) ((Observer) arrlocal[i]). Update ( This, ARG); } Public synchronized void deleteobservers() {obs.removeallelements (); }protected synchronized void setchanged() {changed =true; }protected synchronized void clearchanged() {changed =false; } Public synchronized Boolean hasChanged() {returnChanged }/** * Returns The number of observers of this <tt>Observable</tt> object.     * * @return The number of observers of this object. */     Public synchronized int countobservers() {returnObs.size (); }}
Implementation of the Myobserver viewer object
package com.daming.java.observer;publicclass MyObserver implements Observer{    @Override    publicvoidupdate(Observable observable, Object arg) {        System.out.println("observable :""arg :" + arg);    }}
Implementation of the MyObserver2 viewer object
package com.daming.java.observer;publicclass MyObserver2 implements Observer{    @Override    publicvoidupdate(Observable observable, Object arg) {        System.out.println("observable2 :""arg2 :" + arg);    }}
Implementation of the Testobserver class
 PackageCom.daming.java.observer; Public  class testobserver {    /** * @param args * *     Public Static void Main(string[] args) {Observable Observable =NewObservable (); Myobserver Myobserver =NewMyobserver (); MyObserver2 MyObserver2 =NewMyObserver2 ();        Observable.addobserver (Myobserver);        Observable.addobserver (MYOBSERVER2);        Observable.setchanged (); Observable.notifyobservers ( -);        Observable.setchanged (); Observable.notifyobservers ("I am daming"); }}
Log input Result:
Observable2:com. Daming. Java. Observer. Observable@14318BBARG2: -Observable:com. Daming. Java. Observer. Observable@14318Bbarg: -Observable2:com. Daming. Java. Observer. Observable@14318Bbarg2:i am Damingobservable:com. Daming. Java. Observer. Observable@14318Bbarg:i am Daming

Java source code in the above codes is the push mode, of course, source code also has pull mode, that is, the mode of active query. Pull mode is like the broadcast, through the OnReceive () method to pull up some actions, as well as contentobserver can pull mode, when the database changes, through the onchange () method to invoke some operations.

--and then we'll look at the asynchronous observer pattern in Android.

Contentobserver is the asynchronous observer pattern, what is the benefit of an async observer? does not block the observer's callback. There will be blocking issues in the synchronization notification, the response method of each observer is serial, if there is a observer time-consuming words will block the other observer receiver, so it is possible to cause a bug, so in the design of the time to consider more, Consider using the asynchronous observer pattern to make concurrent processing faster; We learn the next asynchronous observer pattern with a simple demo:

Let's take a look at observer, which is an abstract class in Android.
 PackageCn.daming.observer.design;ImportAndroid.os.Handler;ImportAndroid.util.Log; Public Abstract  class Observer {    PrivateHandler Mhandler; Public Observer(Handler Handler)    {Mhandler = handler; } Public void OnChange() {    } Public Final void Dispatchchange() {LOG.V ("Daming","Observer Dispatchchange is mhandler== null:"+ (Mhandler = =NULL));if(Mhandler = =NULL) {OnChange (); }Else{Mhandler.post (NewNotificationrunnable ()); }    }Private Final  class notificationrunnable implements Runnable {        @Override         Public void Run() {LOG.V ("Daming","Notificationrunnable Dispatchchange is run ... "); Observer. This. OnChange (); }    }}
Then take a look at the implementation of the Observerservice class:
 PackageCn.daming.observer.design;ImportJava.util.ArrayList;ImportJava.util.List;ImportAndroid.util.Log; Public  class observerservice {    Private intMstate;PrivateList<observer> mobservers =NewArraylist<observer> (); Public Final void Registerobserver(Observer Observer) {if(!mobservers.contains (Observer))        {MOBSERVERS.ADD (Observer); }    } Public Final void Unregisterobserver(Observer Observer) {LOG.V ("Daming","Observerservice unregisterobserver:");    MOBSERVERS.REMOVE (Observer); } Public void Notifychange() { for(Observer observer:mobservers)        {Observer.dispatchchange (); }    } Public int getState() {returnMstate; } Public void setState(intState) {mstate = state;    Notifychange (); }}
Finally, let's write the test class Firstactivity:
 PackageCn.daming.observer.design;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportCOM.DAMING.DESIGNTRANING.R; Public  class firstactivity extends Activity {    PrivateObserverservice Mobserverservice;PrivateButton Mbutton;Private intMstate =0;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Mbutton = (Button) Findviewbyid (R.id.button); Mobserverservice =NewObserverservice ();        Mobserverservice.registerobserver (Mfirstobserver);        Mobserverservice.setstate (++mstate); Mbutton.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v)            {mobserverservice.setstate (++mstate);    }        }); }@Override    protected void OnDestroy() {Super. OnDestroy ();    Mobserverservice.unregisterobserver (Mfirstobserver); }@Override    protected void Onresume() {Super. Onresume (); }@Override    protected void OnStop() {Super. OnStop (); }PrivateObserver Mfirstobserver =NewObserver (NewHandler ()) {@Override         Public void OnChange() {intState = Mobserverservice.getstate (); LOG.V ("Daming","Firstobserver OnChange is the Run state:"+ state); }    };}

Summary: By handler to implement the asynchronous observer pattern, that is, the construction of the Observer object when a handler object, so at the time of the callback, the handler to send the asynchronous message on the main thread to perform the corresponding operation.

Observer Pattern--java Design pattern

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.