android开发中使用java观察者模式

2019-12-10 20:10:04王冬梅

   }
  }
 }

 /** detach all observers */
 public void unRegisterAll() {
  synchronized(obserList) {
   obserList.clear();
  }
 }

 /** Ruturn the size of observers */
 public int countObservers() {
  synchronized(obserList) {
   return obserList.size();
  }
 }

 /**
  * notify all observer (通知所有观察者,在子类中实现)
  * @param objs
  */
 public abstract void notifyObservers(Object... objs);

 /**
  * notify one certain observer (通知某一个确定的观察者)
  * @param cls
  * @param objs
  */
 public abstract void notifyObserver(Class<?> cls, Object... objs);

 /**
  * notify one certain observer
  * @param cls
  * @param objs
  */
 public abstract <T> void notifyObserver(T t, Object... objs);
}

//目标被观察者
public class ConcreteObservable extends Observable {

 private static ConcreteObservable instance = null;
 private ConcreteObservable() {}
 public static synchronized ConcreteObservable getInstance() {
  if (instance == null) {
   instance = new ConcreteObservable();
  }
  return instance;
 }

 @Override
 public <T> void notifyObserver(T t, Object... objs) {
  // TODO Auto-generated method stub
  if (t == null) throw new NullPointerException();
  this.notifyObserver(t.getClass(), objs);
 }

 @Override
 public void notifyObservers(Object... objs) {
  // TODO Auto-generated method stub
  for (Class<?> cls : obserList) {
   this.notifyObserver(cls, objs);
  }
 }


 @Override  //通过java反射机制实现调用
 public void notifyObserver(Class<?> cls, Object... objs) {
  // TODO Auto-generated method stub
  if (cls == null) throw new NullPointerException();
  Method[] methods = cls.getDeclaredMethods();
  for (Method method : methods) {
   if (method.getName().equals("update")) {
    try {