Analysis of Android source code design patterns and practices (12)

Source: Internet
Author: User

Analysis of Android source code design patterns and practices (12)
Chapter 2 observer Mode

The observer mode is a mode with very high usage. It is most commonly used in GUI systems and subscription-publishing systems. Because one important role of this pattern is decoupling, it will be decoupled by the observer and the observer, so that the dependencies between them are smaller and even less dependent. For example, Android open-source projects such as EventBus, Otto, and AndroidEventBus use the observer mode at the core of RxJava responsive programming.

1. Definition

The observer mode is a behavior-class mode that defines a one-to-many dependency between objects so that each time an object changes its state, all objects dependent on it will be notified and automatically updated.

2. Use Cases

(1) In associated behavior scenarios, it should be noted that association behavior can be split rather than "combined.

(2) multi-level event triggering scenarios.

(3) Cross-system message exchange scenarios, such as message queues and event bus processing mechanisms.

3. Simple implementation

Here is an example of a follow-up drama. We usually subscribe to or follow the latest TV series. When the TV series are updated, they will be pushed to us as soon as possible.

Abstract observer class

/*** Abstract observer class, which defines an interface for all specific observers, update yourself */public interface Observer {/*** with an update ** @ param message */public void update (String message );}

Abstract observer class

/*** Abstract The Observer class */public interface Observable {/*** push message ** @ param message content */void push (String message ); /*** subscribe ** @ param observer subscriber */void register (Observer observer );}

Specific observer class

/*** Specific Observer class, that is, subscriber */public class User implements Observer {@ Override public void update (String message) {System. out. println (name + "," + message + "updated! ") ;}// Subscriber name private String name; public User (String name) {this. name = name ;}}

Specific observer class

/*** The specific observer class, that is, the subscribed Program */public class Teleplay implements Observable {private List
  
   
List = new ArrayList
   
    
(); // Store the subscriber @ Override public void push (String message) {for (Observer observer: list) {observer. update (message) ;}@ Override public void register (Observer observer) {list. add (observer );}}
   
  

Implementation

Public class Client {public static void main (String [] args) {// observer. This is the TV series subscribed to by the user. Teleplay teleplay = new Teleplay (); // observer, here is the subscriber User user1 = new User ("James"); User user2 = new User ("Xiao Guang"); User user3 = new User ("Xiao Lan "); // subscribe to teleplay. register (user1); teleplay. register (user2); teleplay. register (user3); // push new message teleplay. push ("xxx TV series ");}}

Result

James and xxx TV series updated! Xiaoguang, xxx TV series updated! Xiaolan and xxx TV series updated!

From the code above, we can see that one-to-many message pushing is implemented. The push messages depend on abstract classes such as Observer and Observable, and the User and Teleplay are not coupled at all, this ensures the flexibility and scalability of the subscription system.

4. Observer mode in Android Source Code 1. BaseAdapter

BaseAdapter I believe everyone is familiar with it. In the ListView adapter, we all inherit it. The following is a simple analysis.

BaseAdapter code:

Public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter {// dataset observer private final DataSetObservable mDataSetObservable = new DataSetObservable (); public boolean hasStableIds () {return false;} public void observer (DataSetObserver observer) {mDataSetObservable. registerObserver (observer);} public void unregisterDataSetObserver (DataSetObserver observer) {mDataSetObservable. unregisterObserver (observer);}/*** when the dataset changes, notify all Observers */public void notifyDataSetChanged () {mDataSetObservable. notifyChanged ();}

Let's take a look at the mDataSetObservable. policychanged () method:

public class DataSetObservable extends Observable
  
    {    /**     * Invokes {@link DataSetObserver#onChanged} on each observer.     * Called when the contents of the data set have changed.  The recipient     * will obtain the new contents the next time it queries the data set.     */    public void notifyChanged() {        synchronized(mObservers) {            // since onChanged() is implemented by the app, it could do anything, including            // removing itself from {@link mObservers} - and that could cause problems if            // an iterator is used on the ArrayList {@link mObservers}.            // to avoid such problems, just march thru the list in the reverse order.            for (int i = mObservers.size() - 1; i >= 0; i--) {                mObservers.get(i).onChanged();            }        }    }
  

We can see that all the observers are traversed in mDataSetObservable. policychanged () and their onChanged () are called to tell the observer what happened.

The following code shows how the observer comes from the setAdapter method:

@ Override public void setAdapter (ListAdapter adapter) {if (mAdapter! = Null & mDataSetObserver! = Null) {mAdapter. unregisterDataSetObserver (mDataSetObserver);} resetList (); mRecycler. clear (); if (mHeaderViewInfos. size ()> 0 | mFooterViewInfos. size ()> 0) {mAdapter = new HeaderViewListAdapter (mHeaderViewInfos, mFooterViewInfos, adapter);} else {mAdapter = adapter;} mOldSelectedPosition = INVALID_POSITION; region = INVALID_ROW_ID; // AbsListView # setAdapter will update choice mo De states. super. setAdapter (adapter); if (mAdapter! = Null) {mAreAllItemsSelectable = mAdapter. areAllItemsEnabled (); mOldItemCount = mItemCount; mItemCount = mAdapter. getCount (); checkFocus (); mDataSetObserver = new AdapterDataSetObserver (); mAdapter. registerDataSetObserver (mDataSetObserver); // register the observer ...... omitted}

AdapterDataSetObserver is defined in the parent class AbsListView of ListView. It is a dataset observer with the code:

class AdapterDataSetObserver extends AdapterView
  
   .AdapterDataSetObserver {        @Override        public void onChanged() {            super.onChanged();            if (mFastScroller != null) {                mFastScroller.onSectionsChanged();            }        }        @Override        public void onInvalidated() {            super.onInvalidated();            if (mFastScroller != null) {                mFastScroller.onSectionsChanged();            }        }    }
  

It is the AdapterDataSetObserver of the parent class AdapterView inherited from AbsListView. The Code is as follows:

Class AdapterDataSetObserver extends DataSetObserver {private Parcelable mInstanceState = null; // As mentioned above, the onChanged method of all observers is called when the notifyDataSetChanged method of the Adapter is called, the core implementation is here @ Override public void onChanged () {mDataChanged = true; mOldItemCount = mItemCount; // obtain the number of data in the Adapter, mItemCount = getAdapter (). getCount (); // Detect the case where a cursor that was previusly invalidated has // been repopulated With new data. if (AdapterView. this. getAdapter (). hasStableIds () & mInstanceState! = Null & mOldItemCount = 0 & mItemCount> 0) {AdapterView. this. onRestoreInstanceState (mInstanceState); mInstanceState = null;} else {rememberSyncState ();} checkFocus (); // relayout the AdapterView components such as ListView and GridView ();} // The Code omitting public void clearSavedState () {mInstanceState = null ;}}

When the data of the ListView changes, call the notifyDataSetChanged function of the Adapter. This function then calls the notifyChanged function of DataSetObservable, which calls the onChanged method of all observers (AdapterDataSetObserver. This is an observer mode!

5. Summary 1. Advantages

(1) The observer and the observer are abstract coupling to cope with business changes.

(2) enhanced system flexibility and scalability.

2. Disadvantages

In the Application observer mode, you need to consider the issues of development efficiency and operation efficiency. The program contains one observer, multiple observers, and the development and debugging contents are complex, in addition, notifications of messages in Java are generally executed sequentially, so an observer gets stuck, which affects the overall execution efficiency. In this case, asynchronous implementation is generally used.

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.