Android设计模式系列--观察者模式

来源:互联网 发布:数组转化为json 编辑:程序博客网 时间:2024/04/27 16:17

最近做一个android项目遇到的一种设计模式,通过在UI中注册对某事件的监听,当该事件发生时,自动触发UI执行相关的操作,通过在网上搜索,弄明白了这用了观察者模式,现将项目中该模式的代码实现总结一下:

首先要定义一个容器(ArrayList、Map等)mListeners来存放监听器;

private ArrayList<GroupInfoUpdateListener> mListeners;public PushStatusClient(Context context) {        mContext = context;        mListeners = new ArrayList<GroupInfoUpdateListener>();    }

然后定义监听器的接口,里面封装监听器要监听的事件;

public interface GroupInfoUpdateListener {        public void onGroupListUpdate();        public void onGroupAttrUpdate(String groupDN);        public void onGroupMemberUpdate(String groupDN);    }

最后定义一个监听器注册函数,将监听器都注册到容器中去;

public void registerGroupInfoUpdateListener(GroupInfoUpdateListener listener) {        for (GroupInfoUpdateListener lis : mListeners) {            if (lis.equals(listener)) {                return;            }        }        mListeners.add(listener);    }

被观察的对象通过遍历容器中的监听器,调用监听器接口中的方法;

private void onProcessPushMsg(){        for (GroupInfoUpdateListener listener : mListeners) {            listener.onGroupListUpdate();        }        for (GroupInfoUpdateListener listener : mListeners) {            listener.onGroupAttrUpdate(groupDN);        }        for (GroupInfoUpdateListener listener : mListeners) {            listener.onGroupMemberUpdate(groupDN);        }    }

作为观察者只需要将监听器注册到容器中去,然后复写监听器中的方法就可以了;

private PushStatusClient mPushStatusClient;mPushStatusClient = EcontactFactory.getInstance().getPushStatusClient();mPushStatusClient.registerGroupInfoUpdateListener(new GroupInfoUpdateListener() {        public void onGroupListUpdate() {            notifyUpdatingGroupList();        };        public void onGroupAttrUpdate(String groupIdList) {            notifyUpdatingGroupAttr(groupIdList);        };        public void onGroupMemberUpdate(String groupIdList) {            notifyUpdatingGroupMember(groupIdList);        };    });
0 0
原创粉丝点击