/** Observer mode * defines a (subject)-to-many (observer) dependency between objects. When the status of an object changes, therefore, the * objects dependent on it are notified and automatically updated **. Of course, MVC is only an instance of the observer mode. The problem to be solved in the Observer mode is: * establish a one-to-many (observer) Dependency relationship, and when "one" changes, * many "one" dependencies can also be changed synchronously. The most common example is: When statistical analysis is performed on the same group of data, * We hope to provide multiple forms of representation (for example, statistical display of tables, statistical display of bar charts, and percentage statistical display ). * These representations depend on the same group of data. Of course, when the data changes, the display of all statistics can be changed at the same time. * The Observer mode solves this problem. ** Applicability: * 1. when an abstract model has two aspects, one of which depends on the other. * encapsulate the two into independent objects so that they can change and use them independently. ** 2. when changing an object, you need to change other objects at the same time without knowing how many objects need to be changed. ** 3. when an object must notify other objects, it cannot assume who the other objects are ** participants: * 1. subject (target) * an observer who knows the object. Multiple observers can observe the same object. * interfaces for registering and deleting the object are provided. ** 2. observer * defines an updated interface for objects that need to be notified when the target changes ** 3. concretesubject (specific target) * stores the relevant State to each concreteobserver object * sends a notification to each observer when its state is changed ** 4. concreteobserver (Specific observer) * maintains a reference to the concreteobserver object * storage-related status, these statuses should be consistent with the target status. * The interface for updating observer is consistent with the target status ****/
I will add the UML diagram when I have time.
Next let's take a look at the observer mode used by Android.
Datasetobserver, object (observable <t>), and datasetobserverable)
Observer (observer)Datasetobserver abstracts two methods: one is to observe the data change method, and the other is to observe the data into invalid (or unavailable) method.
Source code path: Framework/base/CORE/Java/Android/database/datasetobserver. Java
package android.database;/** * Receives call backs when a data set has been changed, or made invalid. The typically data sets * that are observed are {@link Cursor}s or {@link android.widget.Adapter}s. * DataSetObserver must be implemented by objects which are added to a DataSetObservable. */public abstract class DataSetObserver { /** * This method is called when the entire data set has changed, * most likely through a call to {@link Cursor#requery()} on a {@link Cursor}. */ public void onChanged() { // Do nothing } /** * This method is called when the entire data becomes invalid, * most likely through a call to {@link Cursor#deactivate()} or {@link Cursor#close()} on a * {@link Cursor}. */ public void onInvalidated() { // Do nothing }}
Subject (target), Observable <t> is a generic abstract class. Its main function is to register and revoke observer.
Source code path: Framework/base/CORE/Java/Android/database/observable. Java
package android.database;import java.util.ArrayList;/** * Provides methods for (un)registering arbitrary observers in an ArrayList. */public abstract class Observable<T> { /** * The list of observers. An observer can be in the list at most * once and will never be null. */ protected final ArrayList<T> mObservers = new ArrayList<T>(); /** * Adds an observer to the list. The observer cannot be null and it must not already * be registered. * @param observer the observer to register * @throws IllegalArgumentException the observer is null * @throws IllegalStateException the observer is already registered */ public void registerObserver(T observer) { if (observer == null) { throw new IllegalArgumentException("The observer is null."); } synchronized(mObservers) { if (mObservers.contains(observer)) { throw new IllegalStateException("Observer " + observer + " is already registered."); } mObservers.add(observer); } } /** * Removes a previously registered observer. The observer must not be null and it * must already have been registered. * @param observer the observer to unregister * @throws IllegalArgumentException the observer is null * @throws IllegalStateException the observer is not yet registered */ public void unregisterObserver(T observer) { if (observer == null) { throw new IllegalArgumentException("The observer is null."); } synchronized(mObservers) { int index = mObservers.indexOf(observer); if (index == -1) { throw new IllegalStateException("Observer " + observer + " was not registered."); } mObservers.remove(index); } } /** * Remove all registered observer */ public void unregisterAll() { synchronized(mObservers) { mObservers.clear(); } }}
Concreatesubject (target)The implementation method is the same as that of oberver, But It notifies every oberver in the arraylist <observer> to execute their respective actions.
Source code path: Framework/base/CORE/Java/Android/database/datasetobservable. Java
package android.database;/** * A specialization of Observable for DataSetObserver that provides methods for * invoking the various callback methods of DataSetObserver. */public class DataSetObservable extends Observable<DataSetObserver> { /** * Invokes onChanged on each observer. Called when the data set being observed has * changed, and which when read contains the new state of the data. */ 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(); } } } /** * Invokes onInvalidated on each observer. Called when the data set being monitored * has changed such that it is no longer valid. */ public void notifyInvalidated() { synchronized (mObservers) { for (int i = mObservers.size() - 1; i >= 0; i--) { mObservers.get(i).onInvalidated(); } } }}
Concreateobserver (Specific observer)A specific observer's task is a class that actually executes the action, which is generally implemented by the developer based on the actual situation. Android also provides implementation examples.
Source code path:
Framework/base/CORE/Java/Android/widget/abslistview. Java
class AdapterDataSetObserver extends AdapterView<ListAdapter>.AdapterDataSetObserver { @Override public void onChanged() { super.onChanged(); if (mFastScroller != null) { mFastScroller.onSectionsChanged(); } } @Override public void onInvalidated() { super.onInvalidated(); if (mFastScroller != null) { mFastScroller.onSectionsChanged(); } } }
Framework/base/CORE/Java/Android/widget/adapterview. Java
class AdapterDataSetObserver extends DataSetObserver { private Parcelable mInstanceState = null; @Override public void onChanged() { mDataChanged = true; mOldItemCount = mItemCount; mItemCount = getAdapter().getCount(); if (DBG) { Xlog.d(TAG, "AdapterView onChanged: mOldItemCount = " + mOldItemCount + ",mItemCount = " + mItemCount + ",getAdapter() = " + getAdapter() + ",AdapterView = " + AdapterView.this, new Throwable("onChanged")); } // Detect the case where a cursor that was previously 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(); requestLayout(); } @Override public void onInvalidated() { mDataChanged = true; if (DBG) { Xlog.d(TAG, "AdapterView onInvalidated: mOldItemCount = " + mOldItemCount + ",mItemCount = " + mItemCount + ",getAdapter() = " + getAdapter() + ",AdapterView = " + AdapterView.this, new Throwable("onInvalidated")); } if (AdapterView.this.getAdapter().hasStableIds()) { // Remember the current state for the case where our hosting activity is being // stopped and later restarted mInstanceState = AdapterView.this.onSaveInstanceState(); } // Data is invalid so we should reset our state mOldItemCount = mItemCount; mItemCount = 0; mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkFocus(); requestLayout(); } public void clearSavedState() { mInstanceState = null; } }
Instance:
Type application is a familiar baseadapter. baseadapter is associated with a datasetobservable object and implements two methods: registerdatasetobserver and unregisterdatasetobserver. The method policydatasetchanged indirectly calls the onchange () of the observer implementer () method To change the notification data. When the combination of listview and baseadapter is used, when the item of baseadapter changes, we often call yydatasetchanged () to notify listview to refresh.
However, however, we have never called the registerdatasetobserver (datasetobserver observer) of baseadapter to register the observer. How can listview receive the notification and perform the refresh action?
Let's take a look at what listview has done.
/** * Sets the data behind this ListView. * * The adapter passed to this method may be wrapped by a {@link WrapperListAdapter}, * depending on the ListView features currently in use. For instance, adding * headers and/or footers will cause the adapter to be wrapped. * * @param adapter The ListAdapter which is responsible for maintaining the * data backing this list and for producing a view to represent an * item in that data set. * * @see #getAdapter() */ @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; mOldSelectedRowId = INVALID_ROW_ID; // AbsListView#setAdapter will update choice mode states. super.setAdapter(adapter); if (mAdapter != null) { mAreAllItemsSelectable = mAdapter.areAllItemsEnabled(); mOldItemCount = mItemCount; mItemCount = mAdapter.getCount(); checkFocus(); mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); mRecycler.setViewTypeCount(mAdapter.getViewTypeCount()); int position; if (mStackFromBottom) { position = lookForSelectablePosition(mItemCount - 1, false); } else { position = lookForSelectablePosition(0, true); } setSelectedPositionInt(position); setNextSelectedPositionInt(position); if (mItemCount == 0) { // Nothing selected checkSelectionChanged(); } } else { mAreAllItemsSelectable = true; checkFocus(); // Nothing selected checkSelectionChanged(); } requestLayout(); }
Note the following three lines:
mAdapter = adapter;
mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver);
When setadapter (listadapter adapter) is used, baseadapter registers adapterdatasetobserver () at the same time. As for how adapterdatasetobserver notifies listvew and each subitem to refresh (invalidate, the content involved here is beyond the scope of the article. For details, refer to the source code.
In fact, there are many places for Android to use datasetobserver, such as cursor, webview, adapter.