Common design Patterns in Android development (III)--observer mode

Source: Internet
Author: User
Tags eventbus

Let's look at the definition of this pattern.

定义对象间的一种一对多的依赖关系,当一个对象的状态发送改变时,所有依赖于它的对象都能得到通知并被自动更新

Let's start with a few scenarios.

    • Scenario 1: There is a short message service, such as the weather forecast service, once you subscribe to the service, you only pay monthly, after the fee, once a day, once the weather information updates, it will be in time to 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 above two scenarios, one thing in common is that we don't have to focus on what we're interested in all the time, and all we have to do is subscribe to things we're interested in, such as weather forecasts, magazines, and so on, once we've subscribed to things that change, such as new weather forecasts, new magazines, etc. The subscribed items are immediately notified to the subscribers, that is, us. And these subscribed things can have multiple subscribers, that is, a one-to-many relationship. Of course, in strict sense, this pair can contain one-to-many, because one-to-many exceptions, no special instructions, this article's a one-to-many contains a one-on.

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

Then we look at several important components of the observer pattern.

    • Observers, we call it observer, and sometimes we call it subscribers, subscriber

    • The Observer, we call it observable, what can be observed, sometimes called the subject, namely subject

As for the specific implementation of the observer pattern, here take you to realize the scenario one, in fact, Java provides the observable class and observer interface for us to quickly implement the pattern, but in order to deepen 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 observer, and we want the observer to be generic and define it as generics. The register and the unregister method should be exposed internally for the observer to subscribe to and unsubscribe from, as for the observer's preservation, directly with the ArrayList, in addition, when the subject content sent changes, will immediately notify the observer to respond, Therefore, a notifyobservers method should be exposed, the specific implementation of the above method is shown in the code below.

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);        }    }}

And our observer 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 subject of the subscription sends the transformation, the interface is recalled.

Let's use this, we define a weather change theme, that is, the observer, there are two observers observe the weather change, once transformed, print out the weather information, be sure to call the Observer's register for registration, otherwise you will not receive the transformation information. And once you are not interested, call the Unregister method to cancel the registration directly

public class Main {public static void main (String [] args) {observable<weather> observable=new Observable        <Weather> (); Observer<weather> observer1=new observer<weather> () {@Override public void onUpdate (Obs            Ervable<weather> observable, Weather data) {SYSTEM.OUT.PRINTLN ("Observer 1:" +data.tostring ());        }        }; Observer<weather> observer2=new observer<weather> () {@Override public void onUpdate (Obs            Ervable<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 ("cloudy");        Observable.notifyobservers (Weather1);        Observable.unregister (Observer1); Weather weather2=new Weather ("Typhoon");    Observable.notifyobservers (WEATHER2); }}

The final output is not a problem, as follows

观察者1:Weather{description=’晴转多云’}观察者2:Weather{description=’晴转多云’}观察者1:Weather{description=’多云转阴’}观察者2:Weather{description=’多云转阴’}观察者2:Weather{description=’台风’}

Let's take a look at the viewer pattern for Android applications. Let's start with the simplest. Remember that 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 a strict sense, this is most of a callback, but we can think of it as a one-way observer pattern, that is, a single observer.

In fact, as long as the set of sets of listener methods can only be called callbacks, 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();    }}

Similar methods are many, are the Add Listener series method, here is no longer an example.

Another place is the Android broadcasting mechanism, its essence is the Observer mode, here for the sake of simplicity, directly take the local broadcast code description, that is, Localbroadcastmanager.

Our usual use of local broadcast is mainly 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 unregister, and then send the broadcast directly using Sendbroadcast, and after sending the broadcast, the registered broadcast receives the corresponding broadcast message, which is the typical observer pattern.

Let's take a 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 pattern.

Three typical methods of the observer pattern it has, that is, register, unregister, send event

EventBus.getDefault().register(Object subscriber);EventBus.getDefault().unregister(Object subscriber);EventBus.getDefault().post(Object event);

In short, the observer pattern in Android is still being used very often.

Common design Patterns in Android development (III)--observer mode

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.