android开发中使用java观察者模式
本文导语: 代码如下://观察者,需要用到观察者模式的类需实现此接口public interface Observer { void update(Object... objs);} //被观察者(一个抽象类,方便扩展)public abstract class Observable { public final ArrayList>(); /** Attach Observer (通过实例注册观...
//观察者,需要用到观察者模式的类需实现此接口
public interface Observer {
void update(Object... objs);
}
//被观察者(一个抽象类,方便扩展)
public abstract class Observable {
public final ArrayList>();
/** Attach Observer (通过实例注册观察者)
* Notice: ob can't be null ,or it will throw NullPointerException
* */
public void registerObserver(T ob) {
if (ob == null) throw new NullPointerException();
this.registerObserver(ob.getClass());
}
/**
* Attach Observer(通过Class注册观察者)
* @param cls
*/
public void registerObserver(Class cls) {
if (cls == null) throw new NullPointerException();
synchronized(obserList) {
if (!obserList.contains(cls)) {
obserList.add(cls);
}
}
}
/** Unattach Observer (注销观察者)
* Notice:
* It reverses with attachObserver() method
* */
public void unRegisterObserver(T ob) {
if (ob == null) throw new NullPointerException();
this.unRegisterObserver(ob.getClass());
}
/** Unattach Observer(注销观察者,有时候在未获取到实例使用)
* Notice:
* It reverses with attachObserver() method
* */
public void unRegisterObserver(Class cls) {
if(cls == null) throw new NullPointerException();
synchronized(obserList){
Iterator