观察者(Observer)模式又名发布-订阅(Publish/Subscribe)模式。
1.定义
Define a one-to-many dependency between objects so that when one object changes state, all its dependents aer notified and updated automatically.
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
2. 组成部分
1)抽象目标角色(Subject):目标角色知道它的观察者,可以有任意多个观察者观察同一个目标。并且提供注册和删除观察者对象的接口。目标角色往往由抽象类或者接口来实现。
2)抽象观察者角色(Observer):为那些在目标发生改变时需要获得通知的对象定义一个更新接口。抽象观察者角色主要由抽象类或者接口来实现。
3)具体目标角色(Concrete Subject):将有关状态存入各个Concrete Observer对象。当它的状态发生改变时, 向它的各个观察者发出通知。
4)具体观察者角色(Concrete Observer):存储有关状态,这些状态应与目标的状态保持一致。实现Observer的更新接口以使自身状态与目标的状态保持一致。在本角色内也可以维护一个指向Concrete Subject对象的引用。
3.Java代码
接下来我们自己来模拟一个观察者模式(Observer)[其中涉及到2个接口,2个实现类,还有1个测试类]
1)Subject接口
/**
* 抽象主题角色
* @author jiangqq
*
*/
public interface Subject {
/**
* 注册添加观察者
* @param observer
*/
public void addObserver(Observer observer);
/**
* 刪除观察者
* @param observer
*/
public void removeObserver(Observer observer);
/**
* 对已经注册的观察者对象发送通知
* @param observer
*/
public void notifyObserver(String str);
}
2)具体主题角色ConcreteSubject
/**
* 具体主题角色 :主要功能是添加,删除观察者,并且当主题角色内部状态发生改变的时候,来通知观察者
* @author jiangqq
*
*/
public class ConcreteSubject implements Subject {
List<Observer> list=new ArrayList<Observer>();
@Override
public void addObserver(Observer observer) {
list.add(observer);
}
@Override
public void removeObserver(Observer observer) {
list.remove(observer);
}
@Override
public void notifyObserver(String str) {
for(Observer observer:list){
observer.update(str);
}
}
}
3)抽象观察者角色(Observer)
/**
* 抽象观察者角色
* @author jiangqq
*
*/
public interface Observer {
/**
* 当观察者接受到主题发来的通知,自动调用update()来更新自己
*/
public void update(String str);
}
4)具体观察者角色(ConcreteObserver)
public class ConcreteObserver implements Observer {
@Override
public void update(String str) {
System.out.println("收到的信息是:"+str);
}
}
5)测试类
public class TestCustomObserver {
public static void main(String[] args) {
Subject sub=new ConcreteSubject();
Observer ob1=new ConcreteObserver();
Observer ob2=new ConcreteObserver();
Observer ob3=new ConcreteObserver();
//注册三个观察者,模拟当主题角色发送通知,三个观察者更新自己
sub.addObserver(ob1);
sub.addObserver(ob2);
sub.addObserver(ob3);
sub.notifyObserver("今天天氣很好...");
//移除一個观察者
sub.removeObserver(ob1);
sub.notifyObserver("今天天氣不好...");
}
}
运行结果:
4.观察者模式在安卓中的API
抽象观察者角色(Observer)
具体观察者角色(DataSetObserver),
抽象主题角色(Observable< T >抽象类),
具体主题角色(DataSetObserverable),
1)Observer
package java.util;
public interface Observer {
void update(Observable observable, Object data);
}
2)DataSetObserver
package android.database;
public abstract class DataSetObserver {
public void onChanged() {
// Do nothing
}
public void onInvalidated() {
// Do nothing
}
}
3)Observable
import java.util.ArrayList;
public abstract class Observable<T> {
protected final ArrayList<T> mObservers = new ArrayList<T>();
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);
}
}
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);
}
}
public void unregisterAll() {
synchronized(mObservers) {
mObservers.clear();
}
}
}
4)DataSetObservable
package android.database;
public class DataSetObservable extends Observable<DataSetObserver> {
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();
}
}
}
public void notifyInvalidated() {
synchronized (mObservers) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onInvalidated();
}
}
}
}
5.观察者模式在安卓中的潜在应用
平时我们在使用ListView,GridView等时需要构建适配器和关联适配器。在自定义适配器继承BaseAdapter时我们经常使用的一个方法是adapter.notifyDataSetChanged()来通知ListView,GridView等更新数据。但其底层是怎么实现的呢?
BaseAdapter关联了一个DataSetObservable对象,并实现registerDataSetObserver和unregisterDataSetObserver两个方法实现注册和撤销Observer,方法notifyDataSetChanged间接调用Observer的实现者的onChange()方法,以达到通知数据改变的作用。使用ListView和BaseAdapter组合时,当BaseAdapter的item改变时,我们经常会调用notifyDataSetChanged(),通知Listview刷新。
1)构建DataSetObservable对象
private final DataSetObservable mDataSetObservable = new DataSetObservable();
2)注册Observer
public void registerDataSetObserver(DataSetObserver observer) {
mDataSetObservable.registerObserver(observer);
}
3)撤销Observer
public void unregisterDataSetObserver(DataSetObserver observer) {
mDataSetObservable.unregisterObserver(observer);
}
4)通知ListView等更新数据
/**
* 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();
}
但是,但是,但是,我们从来没有调用BaseAdapter的registerDataSetObserver(DataSetObserver observer)注册Observer,那么Listview如何接收到通知,并执行刷新动作呢?
我们来看看ListView做了什么
/**
* 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();
}
注意下面3行
mAdapter = adapter;
mDataSetObserver = new AdapterDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
当我们setAdapter(ListAdapter adapter)时,BaseAdapter同时注册了AdapterDataSetObserver(),至于AdapterDataSetObserver是如何通知Listvew和每个子item刷新(invalidate)的,这里涉及到的内容已经超出文章的范围,具体请查看源码。
其实,Android用到DataSetObserver的地方很多,Cursor,WebView,Adapter,…非常之多。