一個簡單的觀察者模式例子
一:下面的這個類是核心類
public class NotificationCenter {
//static reference for singleton private static NotificationCenter _instance; private static NotificationCenter _instance2; private HashMap<String, ArrayList<NotificationDelegate>> registredObjects; //default c'tor for singleton private NotificationCenter(){ registredObjects = new HashMap<>(); } //returning the reference public static synchronized NotificationCenter defaultCenter(){ if(_instance == null) _instance = new NotificationCenter(); return _instance; } //returning the reference public static synchronized NotificationCenter defaultCenterNew(){ if(_instance2 == null) _instance2 = new NotificationCenter(); return _instance2; } public synchronized void addFucntionForNotification(String notificationName, NotificationDelegate delegate){ ArrayList<NotificationDelegate> list = registredObjects.get(notificationName); if(list == null) { list = new ArrayList<>(); registredObjects.put(notificationName, list); } list.add(delegate); } public synchronized void removeFucntionForNotification(String notificationName, NotificationDelegate r){ if(registredObjects == null){ return ; } ArrayList<NotificationDelegate> list = registredObjects.get(notificationName); if(list != null) { list.remove(r); } } public synchronized void postNotificationName(String notificationName, Object obj){ ArrayList<NotificationDelegate> list = registredObjects.get(notificationName);
// LogUtils.showLog(“==========”,” ” + list);
if(list != null) {
for(NotificationDelegate r: list){
r.update(notificationName,obj);
// LogUtils.showLog(“==========”,” upadate “);
}
}
}
// public synchronized void postNotification(Object obj){
// for(String name: registredObjects.keySet()){
// ArrayList list = registredObjects.get(name);
// if(list!= null){
// for(NotificationDelegate r: list)
// r.update(“”,obj);
// }
// }
// }
}
二:
/**
* Created by dongwanlin on 2016/6/2.
*/
public interface NotificationDelegate {
public void update(String name, Object obj);
}
三:
( 1 )傳送
SmmApplication.center.postNotificationName(FinalConstant.AutoQuotation_Finish, categoryId);
(2)接收
private void registerListener() {
final Gson gson = new Gson();
// 實時更新監聽器
delegate = new NotificationDelegate() {
@Override
public void update(String name, Object obj) {
if (name.equals(FinalConstant.AutoQuotation_Finish)) {
s_page = 1;
getData();
}
}
};
if (SmmApplication.center != null) { SmmApplication.center.addFucntionForNotification(FinalConstant.AutoQuotation_Finish,delegate);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (SmmApplication.center != null) {
SmmApplication.center.removeFucntionForNotification(FinalConstant.AutoQuotation_Finish, delegate);
}
}