一个简单的观察者模式例子

来源:互联网 发布:打考勤软件 编辑:程序博客网 时间:2024/05/22 05:29

一:下面的这个类是核心类
public class NotificationCenter {

//static reference for singletonprivate static NotificationCenter _instance;private static NotificationCenter _instance2;private HashMap<String, ArrayList<NotificationDelegate>> registredObjects;//default c'tor for singletonprivate NotificationCenter(){    registredObjects = new HashMap<>();}//returning the referencepublic static synchronized NotificationCenter defaultCenter(){    if(_instance == null)        _instance = new NotificationCenter();    return _instance;}//returning the referencepublic 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);
}
}

1 0