Ubiquitous Design Pattern in Android development-Observer Pattern

Source: Internet
Author: User
Tags eventbus

Ubiquitous Design Pattern in Android development-Observer Pattern
Ubiquitous Design Pattern in Android development-Singleton pattern: ubiquitous Design Pattern in Android development-Builder Pattern

The Singleton mode and Builder mode are introduced earlier. For more information, see the two links above. This article focuses on the observer mode. Let's take a look at the definition of this mode.

Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it will be notified and automatically updated.

In other words, the definition is often abstract. To have a deep understanding of the definition, You need to practice it yourself.

Let's talk about several scenarios first.

Scenario 1

There is a short message service, such as the weather forecast service. Once you subscribe to this service, you only need to pay by month. After the payment, once the weather information is updated every day, it will send you the latest weather information in time.

Scenario 2

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

One thing we have in common when observing the above two scenarios is that we don't need to pay attention to what we are interested in every moment. What we only need to do is to subscribe to things we are interested in, such as the weather forecast service and magazines, once the subscribed things change, such as new weather forecast information and new magazines, the subscribed things will be immediately notified to the subscriber, that is, we. These subscribed items can have multiple subscribers, that is, the one-to-many relationship. Of course, in a strict sense, this one-to-many can contain one-to-one, because one-to-one is a special case of one-to-many. This article includes one-to-many.

Now, let's look at the definition of the observer mode. Are you suddenly enlightened.

Then let's take a look at several important components of the observer mode.

Observer: we call it an Observer. Sometimes we call it a Subscriber, that is, the Subscriber is an Observer. We call it an Observable, that is, something that can be observed. Sometimes it is also called a topic, subject

As for the implementation of the observer mode, here we will show you how to implement scenario 1. In fact, java providesObservableClass andObserver InterfaceWe can quickly implement this mode, but we do not use these two classes to deepen our impression.

In scenario 1, we are interested in Weather forecast. Therefore, 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 this observer to be generic. The register and unregister methods should be exposed internally for the observer to subscribe to and unsubscribe to. For the observer to save, use ArrayList directly. In addition, when the subject content is sent and changed, will immediately notify the observer to respond, so we should expose a yyobservers method. for the specific implementation of the above method, see the following code.

public class Observable
  
    {    List
   
    > mObservers = new ArrayList
    
     >();    public void register(Observer
     
       observer) {        if (observer == null) {            throw new NullPointerException(observer == null);        }        synchronized (this) {            if (!mObservers.contains(observer))                mObservers.add(observer);        }    }    public synchronized void unregister(Observer
      
        observer) { mObservers.remove(observer); } public void notifyObservers(T data) { for (Observer
       
         observer : mObservers) { observer.onUpdate(this, data); } }}
       
      
     
    
   
  

Our Observer only needs to implement an Observer interface Observer, which is also generic. It is defined as follows.

public interface Observer
  
    {    void onUpdate(Observable
   
     observable,T data);}
   
  

This interface is called back once the subscribed topic is changed.

Let's use it. we defined a theme of weather change, that is, the observer. There are two observers who observe the weather change. Once the change happens, the weather information is printed, be sure to call the observer's register for registration, otherwise the transformation information will not be received. Once you are not interested, call the unregister method to cancel registration.

Public class Main {public static void main (String [] args) {Observable
  
   
Observable = new Observable
   
    
(); Observer
    
     
Observer1 = new Observer
     
      
() {@ Override public void onUpdate (Observable
      
        Observable, Weather data) {System. out. println (Observer 1: + data. toString () ;}}; Observer
       
         Observer2 = new Observer
        
          () {@ Override public void onUpdate (Observable
         
           Observable, Weather data) {System. out. println (observer 2: + data. toString () ;}}; observable. register (observer1); observable. register (observer2); Weather weather = new Weather (clear to cloudy); observable. notifyObservers (weather); Weather weather1 = new Weather (cloudy to overcast); observable. notifyObservers (weather1); observable. unregister (observer1); Weather = new Weather (typhoon); observable. notifyObservers (weatsp2 );}}
         
        
       
      
     
    
   
  

There is no problem with the final output result, as shown below:

Observer 1: Weather {description = 'Clear to cloudy '}
Observer 2: Weather {description = 'Clear to cloudy '}
Observer 1: Weather {description = 'Cloudy to overcast '}
Observer 2: Weather {description = 'Cloudy to overcast '}
Observer 2: Weather {description = 'typhoon '}

Next we will look at the application of the observer mode in android. Let's start with the simplest one. Remember the code for setting click events for a Button.

Button btn=new Button(this);btn.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        Log.e(TAG,click);    }});

In fact, strictly speaking, this is a callback, but we can regard it as a one-to-one observer mode, that is, there is only one observer.

In fact, as long as the set method sets the listener, it can only calculate the callback, but some listener methods are added. This is the observer mode, such as the addOnScrollListener method in RecyclerView.

private List
  
    mScrollListeners;public void addOnScrollListener(OnScrollListener listener) {    if (mScrollListeners == null) {        mScrollListeners = new ArrayList
   
    ();    }    mScrollListeners.add(listener);}public void removeOnScrollListener(OnScrollListener listener) {    if (mScrollListeners != null) {        mScrollListeners.remove(listener);    }}public void clearOnScrollListeners() {    if (mScrollListeners != null) {        mScrollListeners.clear();    }}
   
  

When a rolling event occurs, the observer is triggered to call back the method.

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 many similar methods, all of which are the add listener series methods. Here we will not give an example.

Another aspect is the Broadcast Mechanism of Android, which is essentially the observer mode. For simplicity and convenience, we can directly explain the code of local broadcast, that is, LocalBroadcastManager.

We usually use the following four methods for local broadcasting:

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 a broadcast, call the unregisterReceiver method to cancel registration, and then directly use sendBroadcast to send the broadcast. After the broadcast is sent, the registered broadcast will receive the corresponding broadcast information, which is a typical observer mode. The specific source code is not posted here.

There are still many observer patterns in the android system. If you are interested in exploring them, let's take a look at the observer patterns in some open-source frameworks. When talking about the open-source framework, you should first think of EventBus. Yes, EventBus is also based on the observer mode.

The three typical methods of observer mode are available: Registration, unregistration, and event sending.

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

The internal source code is not expanded. Next, let's take a look at the heavyweight library, which is RxJava. Due to the steep learning curve, this library makes a lot of people look at it.

Create an observer

Observable
  
    myObservable = Observable.create(      new Observable.OnSubscribe
   
    () {          @Override          public void call(Subscriber
     sub) {              sub.onNext(Hello, world!);              sub.onCompleted();          }      }  );  
   
  

Create an observer, that is, a subscriber

Subscriber
  
    mySubscriber = new Subscriber
   
    () {      @Override      public void onNext(String s) { System.out.println(s); }      @Override      public void onCompleted() { }      @Override      public void onError(Throwable e) { }  };  
   
  

Event subscription by the observer

myObservable.subscribe(mySubscriber);  

The specific source code is not expanded, but the source code of the RxJava open-source library is recommended.

In short, the observer mode is frequently used in Android.

 

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.