一接口多实现“事件分发”实现

来源:互联网 发布:网络时时彩代理违法吗 编辑:程序博客网 时间:2024/06/07 05:28


//

public class VoiceStateClient {

private static VoiceStateClient mClient;
//该类单例化
    public static VoiceStateClient getInstance() {
        if (null == mClient) {
            synchronized (VoiceStateClient.class) {
                if (null == mClient) {
                mClient = new VoiceStateClient();
                }
            }
        }
        return mClient;

    }

//定义一个接口

    public interface VoiceStateListener{
    void ReadHDSteate(boolean isHDState);
    }

    public static Set<VoiceStateListener> mStateListeners = new HashSet<VoiceStateListener>();


//每次调用该接口的时候,遍历分发事件,为防止不断添加导致内存泄漏,每次的分发都要清除掉以前的类

    public void setHDStateListener(VoiceStateListener otgReadListener){
    LogUtils.d("====getClassGetName()",otgReadListener.getClass().getName());
        Iterator iterator = mStateListeners.iterator();
        while (iterator.hasNext()) {
        VoiceStateListener listener = (VoiceStateListener)iterator.next();
            if(listener instanceof DialFragment){//DialFragment 实现该接口的fragment,下面对应TestActivity ,mAdapter
                iterator.remove();
            }else if (listener instanceof TestActivity ) {
            iterator.remove();
}else if (listener instanceof mAdapter) {
iterator.remove();
}
        }
        mStateListeners.add(otgReadListener);
    }

}

//实现接口的类中调用,注册监听事件

mClient=SearchRecoderClient.getInstance();
mClient.setSRListener(this);

//在需要的地方调用的时候

for(VoiceStateListener mListener:VoiceStateClient.mStateListeners){
mListener.ReadHDSteate(volteState);
}

最后如果是一对一的接口实现就不需要使用hashset进行遍历分发了。直接处理即可。

原创粉丝点击