DataSetObserver猜想观察者模式
frameworks/base/core/java/android/database/DataSetObserver.java
此类的所有代码为:
public abstract class DataSetObserver{
public void onChanged(){}
public void onInvalidated(){}
}
我在想,谁调用onChanged呢?对于观察者,当数据变动时调用onChanged()吧,那应该有数据变动的地方,insert / update /delete
frameworks/base/core/java/android/widget/AdapterView.java内部类AdapterDataSetObserver继承了此类,但它也只是重写了此类中的两个方法,没有写调用关系。
frameworks/base/core/java/android/database/DataSetObserverable.java
此类的所有代码
DataSetObserverable
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) { for (DataSetObserver observer : mObservers) { observer.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 (DataSetObserver observer : mObservers) { observer.onInvalidated(); } } } }
Observable
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); } ... }
BaseAdapter
public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter { private final DataSetObservable mDataSetObservable = new DataSetObservable(); public boolean hasStableIds() { return false; } public void registerDataSetObserver(DataSetObserver observer) { mDataSetObservable.registerObserver(observer); } public void unregisterDataSetObserver(DataSetObserver observer) { mDataSetObservable.unregisterObserver(observer); } /** * Notifies the attached View that the underlying data has been changed * and it should refresh itself. */ public void notifyDataSetChanged() { mDataSetObservable.notifyChanged(); } public void notifyDataSetInvalidated() { mDataSetObservable.notifyInvalidated(); } ... }
从类BaseAdapter中看,这里的注册和通知动作都是通过DataSetObservable对象的,而DataSetObservable继承了Observable<DataSetObserver>。
因此,要查找那些继承自BaseAdapter,又重写了DataSetObserver的onChanged的函数。