Android中的设计模式——DataSetObservable 观察者模式

ListView类,当我们设置Adapter的时候,注册了观察者:

public void setAdapter(ListAdapter adapter) {
    。。。
    //AdapterDataSetObserver是ListView的基类AdapterView的内部类
    mDataSetObserver = new AdapterDataSetObserver();
    mAdapter.registerDataSetObserver(mDataSetObserver);  //注册一个观察者
    。。。
    requestLayout();//更新视图
} 

ListAdapter是一接口,BaseAdapter继承了它。notifyDataSetChanged方法通过一个外部的方法控制如果适配器的内容改变时需要强制调用getView来刷新每个Item的内容,会重绘控件(还原到初始状态)。
notifyDataSetInvalidated 每当发现数据集监控有改变的情况,比如该数据集不再有效,就会调用此方法,重绘当前可见区域。

public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter {
    private final DataSetObservable mDataSetObservable = new DataSetObservable();

    public void registerDataSetObserver(DataSetObserver observer) {
        mDataSetObservable.registerObserver(observer);
    }

    public void unregisterDataSetObserver(DataSetObserver observer) {
        mDataSetObservable.unregisterObserver(observer);
    }

    /**
     * Notifies the attached observers that the underlying data has been changed
     * and any View reflecting the data set should refresh itself.
     */
    public void notifyDataSetChanged() {
        mDataSetObservable.notifyChanged();
    }
    /**
     * Notifies the attached observers that the underlying data is no longer valid
     * or available. Once invoked this adapter is no longer valid and should
     * not report further data set changes.
     */
    public void notifyDataSetInvalidated() {
        mDataSetObservable.notifyInvalidated();
    }
}

DataSetObservable定义如下:

public class DataSetObservable extends Observable<DataSetObserver> {
    public void notifyChanged() {
        synchronized(mObservers) {
            for (int i = mObservers.size() - 1; i >= 0; i--) {
                mObservers.get(i).onChanged();
            }
        }
    }
    public void notifyInvalidated() {
        synchronized (mObservers) {
            for (int i = mObservers.size() - 1; i >= 0; i--) {
                mObservers.get(i).onInvalidated();
            }
        }
    }
}

这里mObservers.get(i)实际上就是我们ListView中的AdapterDataSetObserver,我们来看看AdapterDataSetObserver(在AbListView中):

class AdapterDataSetObserver extends AdapterView<ListAdapter>.AdapterDataSetObserver {

        public void onChanged() {
            super.onChanged();
            if (mFastScroller != null) {
                mFastScroller.onSectionsChanged();
            }
        }
        public void onInvalidated() {
            super.onInvalidated();
            if (mFastScroller != null) {
                mFastScroller.onSectionsChanged();
            }
        }
}

查看一下android\widget\FastScroller.java的代码

public void onSectionsChanged() {
        mListAdapter = null;
}

你可能感兴趣的:(android)