package jnpf.event; import jnpf.consts.ProjectEventConst; import jnpf.module.ProjectEvent; import java.util.*; import java.util.function.Consumer; /** * 自定义事件注册 */ public class ProjectEventHolder { private ProjectEventHolder() { } /** * {topic:{keymatcher:consumer}} */ private static final Map>> events = new HashMap<>(); /** * 添加事件处理器, 默认主题 */ public static void addEventListener(ProjectEventKeyMatcher keyMatcher, Consumer consumer) { addEventListener(ProjectEventConst.DEFAULT_TOPIC_NAME, keyMatcher, consumer); } /** * 添加事件处理器 */ public static void addEventListener(String topic, ProjectEventKeyMatcher keyMatcher, Consumer consumer) { Map> topicEvents = events.computeIfAbsent(topic, k -> new HashMap<>()); topicEvents.put(keyMatcher, consumer); } /** * 获取事件匹配的处理器, 默认主题 */ public static List> getEventListener(ProjectEvent event) { return getEventListener(ProjectEventConst.DEFAULT_TOPIC_NAME, event); } /** * 获取事件匹配的处理器 */ public static List> getEventListener(String topic, ProjectEvent event) { Map> topicEvents = events.getOrDefault(topic, Collections.emptyMap()); List> consumers = new ArrayList<>(); for (Map.Entry> entry : topicEvents.entrySet()) { if(entry.getKey().isMatch(event)){ consumers.add(entry.getValue()); } } return consumers; } }