定义对象间的一种一个(Subject)对多(Observer)的依赖关系,当一个对象的状态发送改变时,所以依赖于它的对象都得到通知并被自动更新
使用方法:
1、定义一个接口,用来通知观察者。
public interface IObserverAdapter {
void update();
}
2、定义一个类,增加,移除观察者和向观察者们发出通知。
public class Subject {
private List<IObserverAdapter > mIObserverAdapterList;
private static Subject mInstance;
public static synchronized final Subject getInstance() {
if (mInstance == null) {
mInstance = new Subject();
}
return mInstance;
}
public boolean registerIObserverAdapter (IObserverAdapter adapter) {
if(null == adapter) {
return false;
}
mIObserverAdapterList.add(adapter);
return true;
}
public void unRegisterIObserverAdapter(IObserverAdapter adapter) {
if (mIObserverAdapterList.remove(adapter)) {
Log.d("Subject ", "unRegisterIObserverAdapter successfully!");
} else {
Log.d("Subject ", "unRegisterIObserverAdapter error!");
}
}
private void update() {
if(!ListUtil.isEmpty(mIObserverAdapterList)) {
for(IObserverAdapter adapter : mIObserverAdapterList) {
adapter.update();
}
}
}
}
3、最后观察者实现观察接口去观察被观察者。
private class observer implements IObserverAdapter {
private Subject mSubject;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSubject = Subject.getInstance();
mSubject.registerIObserverAdapter(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mSubject != null) {
mSubject .unRegisterIObserverAdapter(this);
}
}
@Override
public void update() {
/**该干嘛干嘛*/
}
}