Java 实现回调监听工具类

首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个抽象的监听接口

监听接口类 Listenable

java 复制代码
import java.util.*;
import java.util.function.Consumer;

public interface Listenable<Listener> {

    WeakHashMap<Object, Set> LISTENERS_WEAK_MAP = new WeakHashMap<>();

    default void registerListener(Listener listener) {
        Objects.requireNonNull(listener);
        Set<Listener> listeners;
        synchronized (LISTENERS_WEAK_MAP) {
            listeners = LISTENERS_WEAK_MAP.get(this);
            if (listeners == null) {
                listeners = new HashSet<>();
                LISTENERS_WEAK_MAP.put(this, listeners);
            }
        }
        synchronized (listeners) {
            listeners.add(listener);
        }
    }

    default void unregisterListener(Listener listener) {
        Objects.requireNonNull(listener);
        Set<Listener> listeners;
        synchronized (LISTENERS_WEAK_MAP) {
            listeners = LISTENERS_WEAK_MAP.get(this);
            if (listeners == null) {
                return;
            }
        }
        synchronized (listeners) {
            listeners.remove(listener);
        }
    }

    default Collection<Listener> getListeners() {
        synchronized (LISTENERS_WEAK_MAP) {
            Set<Listener> listeners = LISTENERS_WEAK_MAP.get(this);
            if (listeners == null) {
                return new HashSet<>();
            }
            return new HashSet<>(listeners);
        }
    }

    default boolean isListenerRegistered(Listener listener) {
        synchronized (LISTENERS_WEAK_MAP) {
            Set<Listener> listeners = LISTENERS_WEAK_MAP.get(this);
            if (listeners == null) {
                return false;
            }
            return listeners.contains(listener);
        }
    }

    default void forEachListener(Consumer<Listener> action) {
        forEachListener(action, true);
    }

    default void forEachListener(Consumer<Listener> action, boolean ignoreException) {
        Objects.requireNonNull(action);
        Iterable<Listener> listeners;
        synchronized (LISTENERS_WEAK_MAP) {
            Set<Listener> values = LISTENERS_WEAK_MAP.get(this);
            if (values == null) {
                return;
            }
            listeners = new ArrayList<>(values);
        }
        for (Listener listener : listeners) {
            try {
                action.accept(listener);
            } catch (Exception e) {
                if (!ignoreException) {
                    throw e;
                }
            }
        }
    }


}

实际用法

用法也比较简单,在自己的实现类 MessageManager 中,写上自定义的回调 OnEventListener,然后再实现通知方法,这样就可以很方便的写各种需要一对多通知的不同类型的回调了

java 复制代码
public class Main {

    public static class MessageManager implements Listenable<MessageManager.OnEventListener> {

        private MessageManager() {}

        private static final MessageManager instance = new MessageManager();

        public static MessageManager getInstance() {
            return instance;
        }

        public void onSuccess(String json) {
            forEachListener(it->it.onSuccess(json));
        }

        public void onError(int code, String error) {
            forEachListener(it->it.onError(code, error));
        }

        public interface OnEventListener {
            void onSuccess(String json);
            void onError(int code, String error);
        }
    }

    public static void main(String[] args) {
        MessageManager.getInstance().registerListener(new MessageManager.OnEventListener() {

            @Override
            public void onSuccess(String json) {
                System.out.println("onSuccess " + json);
            }

            @Override
            public void onError(int code, String error) {
                System.out.println("onError code:" + code + " error:" + error);
            }
        });

        MessageManager.getInstance().onSuccess("My json");
        MessageManager.getInstance().onError(-1, "Error");
    }
}

打印结果

vbnet 复制代码
onSuccess My json
onError code:-1 error:Error
相关推荐
维天说25 分钟前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json
Zane19941 小时前
并发 vs 并行:别再傻傻分不清了,一文讲透 Java 并发编程的第一课
java·后端
噢,我明白了2 小时前
java中Excel的导入和导出(EasyExcel)
java·开发语言·excel
吠品2 小时前
Zabbix Web界面误报Server未运行的排查与解决
java·服务器·数据库
啊湘2 小时前
天气查询API接口 按月Token鉴权 实时天气 物联网可用 文档齐全
java·后端·struts
Java内核笔记2 小时前
告别十亿美元的错误 : Spring Boot 4 空安全 (JSpecify) 实战
java·spring boot·后端
糖果店的幽灵3 小时前
langgraph的 MessagesState 解读
java·开发语言·人工智能·windows·langgraph
极光代码工作室4 小时前
基于SpringBoot的在线博客系统
java·springboot·web开发·后端开发
我是唐青枫4 小时前
Java Spring Security 实战详解:从登录认证到 JWT 权限控制
java·spring
ihuyigui4 小时前
海外签收通知短信接口
android·java·开发语言·前端·数据库·后端