The ubiquitous design pattern in Android development--Observer mode

Source: Internet
Author: User
Tags eventbus
Ubiquitous design Patterns in Android development--the ubiquitous design pattern--builder pattern in the single case model Android development

The previous introduction of the single case mode and builder mode, interested in see the above two links, this article focuses on the Observer model. Let's look at the definition of this pattern first.

Defines a one-to-many dependency between objects, and when the state of an object is sent to change, all objects that depend on it are notified and automatically updated

Or that sentence, the definition is often abstract, to a deep understanding of the definition, you need to practice yourself.

Let's talk a few stories first.

Scenario 1

There is a message service, such as weather forecast service, once you subscribe to the service, you only need to pay monthly, after the payment, every day once the weather information updated, it will promptly send you the latest weather information.

Scenario 2

magazine subscriptions, you only need to subscribe to the Post Office magazine, pay a certain fee, when there is a new magazine, the post Office will automatically send the magazine to your reserved address.

Looking at the top two scenarios, one thing we have in common is that we don't have to focus on what we're interested in all the time, all we need to do is subscribe to things that interest us, such as weather forecasts, magazines, etc., once we subscribe to something that changes, like new weather information, new magazines, The subscribed items will be immediately notified to the Subscriber, that is, us. And these subscribed things can have multiple subscribers, that is, a one-to-many relationship. Of course, in the strictest sense, this one-to-many can include one-to-one, because one-to-one is a one-to-many case, with no special instructions, and a one-to-many couple of this article includes one-to-one.

Now that you look back at the definition of the observer pattern, you are not enlightened.

Then we look at several important components of the observer pattern. The Observer, we call it observer, sometimes we call it the Subscriber, the Subscriber observer, we call it observable, the thing that can be observed, sometimes it's called the subject, that subject

As for the specific implementation of the observer model, here brings you to realize the scene one, in fact Java provides the observable class and Observer interface for us to quickly implement the pattern, but in order to enhance the impression, we do not use these two classes.

The thing we are interested in in Scenario 1 is the weather forecast, so we should define a weather entity class.

public class Weather {
    private String description;

    Public Weather (String description) {
        this.description = description;
    }

    Public String GetDescription () {return
        description;
    }

    public void SetDescription (String description) {
        this.description = description;
    }

    @Override public
    String toString () {return
        "weather{" +
                "description= '" + description + ' \ ' +
                '} ';
    }
}

Then we define our observers, and we want the observer to be universal and define it as generics. The internal should expose the register and the unregister method for the observer to subscribe and unsubscribe, as for the observer's save, directly with the ArrayList, in addition, when the subject content to send changes, will immediately notify the observer to respond, Therefore, should expose a notifyobservers method, the above method realization see the following code.

public class Observable<t> {
    list<observer<t>> mobservers = new arraylist<observer<t> > ();

    public void Register (observer<t> Observer) {
        if (Observer = null) {
            throw new NullPointerException (" Observer = = null ");
        }
        Synchronized (this) {
            if (!mobservers.contains (Observer))
                MOBSERVERS.ADD (Observer);
        }

    Public synchronized void Unregister (observer<t> Observer) {
        mobservers.remove (Observer);
    }

    public void Notifyobservers (T-data) {
        for (observer<t>-observer:mobservers) {
            observer.onupdate (this, data);}}


Our observer, however, simply implements an observer's interface Observer, which is also generic. It is defined as follows.

Public interface observer<t> {
    void onUpdate (observable<t> observable,t data);
}

Once the subscribed subject sends a transform, the interface is recalled.

Let's use it, we define a theme for the weather transformation, that is, the observed, and two observers observe the weather change, and once transformed, print out the weather information, and be sure to call the registered register of the Observer, or you will not receive the transform information. Once you are not interested, call the Unregister method directly to cancel registration can be

public class Main {public static void main (String [] args) {observable<weather> observable=new Observab
        Le<weather> (); Observer<weather> observer1=new observer<weather> () {@Override public void onUpdate (O
            Bservable<weather> observable, Weather data) {SYSTEM.OUT.PRINTLN ("Observer 1:" +data.tostring ());
        }
        }; Observer<weather> observer2=new observer<weather> () {@Override public void onUpdate (O
            Bservable<weather> observable, Weather data) {SYSTEM.OUT.PRINTLN ("Observer 2:" +data.tostring ());

        }
        };
        Observable.register (Observer1);


        Observable.register (OBSERVER2);
        Weather weather=new Weather ("Sunny Turn cloudy");

        Observable.notifyobservers (weather);
        Weather weather1=new Weather ("Doyun");

        Observable.notifyobservers (Weather1);

        Observable.unregister (Observer1); WEather weather2=new Weather ("Typhoon");

    Observable.notifyobservers (WEATHER2);
 }
}

The final output is also not a problem, as follows

The Observer 1:weather{description= ' Sunny turns cloudy '}
The Observer 2:weather{description= ' Sunny turns cloudy '}
Observer 1:weather{description= ' Doyun '}
Observer 2:weather{description= ' Doyun '}
Observer 2:weather{description= ' Typhoon '}

Next we look at the application of the observer pattern to Android. Let's start with the simplest. Remember when we set the Click event code for a button?

Button Btn=new button (this);
Btn.setonclicklistener (New View.onclicklistener () {
    @Override public
    void OnClick (View v) {
        log.e ("TAG") "click");
    }
);

In the strictest sense, this is at best a callback, but we can see it as a one-to-one observer pattern, that is, only one observer.

In fact, as long as the set series of the method of setting up the listener can only be a callback, but there are some listener-type add in, this is the observer mode, such as Recyclerview in the Addonscrolllistener method

Private list<onscrolllistener> mscrolllisteners;
public void Addonscrolllistener (Onscrolllistener listener) {
    if (mscrolllisteners = = null) {
        mscrolllisteners = New Arraylist<onscrolllistener> ();
    }
    Mscrolllisteners.add (listener);
}
public void Removeonscrolllistener (Onscrolllistener listener) {
    if (mscrolllisteners!= null) {
        Mscrolllisteners.remove (listener);
    }
public void Clearonscrolllisteners () {
    if (mscrolllisteners!= null) {
        mscrolllisteners.clear ();
    }
}

Then there is a scrolling event that triggers the observer for the method callback

public abstract Static class Onscrolllistener {public
    void onscrollstatechanged (Recyclerview recyclerview, int newstate) {} public
    void onscrolled (recyclerview recyclerview, int dx, int dy) {}
}

void dispatchonscrolled ( int HRESULT, int vresult) {
    //...
    if (mscrolllisteners!= null) {for
        (int i = Mscrolllisteners.size ()-1; I >= 0; i--) {
            Mscrolllisteners.get (i ). onscrolled (this, HRESULT, Vresult);
}} void dispatchonscrollstatechanged (int state) {
    //...
    if (mscrolllisteners!= null) {for
        (int i = Mscrolllisteners.size ()-1; I >= 0; i--) {
            mscrolllisteners.get (i). onscrollstatechanged (this, state);
        }
    }

There are a lot of similar methods, which are the methods of the Add Listener series, and are no longer examples here.

Another place is the Android broadcast mechanism, which is also the observer model, where, for simplicity and convenience, direct local broadcast code instructions, that is, Localbroadcastmanager.

We usually use the local broadcast mainly is the following four methods

Localbroadcastmanager localbroadcastmanager=localbroadcastmanager.getinstance (this);
Localbroadcastmanager.registerreceiver (broadcastreceiver receiver, intentfilter filter);
Localbroadcastmanager.unregisterreceiver (Broadcastreceiver receiver);
Localbroadcastmanager.sendbroadcast (Intent Intent)

Call the Registerreceiver method to register the broadcast, call the Unregisterreceiver method to cancel the registration, then send the broadcast directly using Sendbroadcast, after sending the broadcast, the registered broadcast will receive the corresponding broadcast information, which is the typical observer mode. The specific source code is not posted here.

There are a lot of observer models in the Android system, and there are lots of interesting things to dig for yourself, and then we'll look at some of the observer patterns in the open source framework. When it comes to open source frameworks, the first thing you should think about is eventbus. Yes, Eventbus is also based on the Observer model.

Three typical methods of observer mode it has, that is, registering, canceling registration, sending events

Eventbus.getdefault (). Register (Object subscriber);
Eventbus.getdefault (). Unregister (Object subscriber);

Eventbus.getdefault (). Post (Object event);

The internal source code also does not expand. Next look at the heavyweight library, it is Rxjava, because the learning curve of the steep, this library let a lot of popularity and halt.

Create a person to be observed

observable<string> myobservable = observable.create (  
    new observable.onsubscribe<string> () {  
        @ Override public  
        void Call (subscriber<. Super String> Sub) {  
            sub.onnext ("Hello, world!");  
            Sub.oncompleted ();  
        }  
);  

Create an observer, which is the subscriber

subscriber<string> mysubscriber = new subscriber<string> () {  
    @Override public  
    void OnNext (String s) {System.out.println (s);}  

    @Override public  
    void oncompleted () {}  

    @Override public  
    void OnError (Throwable e) {}  
};  

Observer subscriptions for events

Myobservable.subscribe (Mysubscriber);  

The specific source also does not expand, but rxjava this open source library source individual or suggest is worth to see.

In short, the observer model in Android is still used very frequently.

Related Article

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.