基于接口的事件机制
基于JDK17
功能梗概
- 简洁:监听方只需实现接口
- 直观:发布方直接调用接口方法
- 方便读:能直接看到当前事件监听方位置
- 类型安全:编译时检查
- 静态调用:EventManager.getEvent() 静态方法
- 高效:线程安全的事件对象缓存
逻辑思想
1. 事件
只需要定义一个事件接口继承EventInterface就可以了,例如
/*** 用户登录事件接口*/
public interface IUserLoginEvent extends EventInterface {/*** 用户登录事件* @param userId 用户ID*/void onUserLogin(Long userId);
}
2. 监听方
对于监听方来讲,不需要关注事件对象,只要实现事件接口就可以了。
例如在 LoginService 中
public Class LoginService implements ILoginEvent {@Overridepublic void onLogin(Long userId) {// 当事件触发的时候,会调用这个方法}
}
3. 发布方
关于发布方来讲,就像正常调用方法一样就可以
public void main(String[] args) {ILoginEvent event = EventManager.getEvent(ILoginEvent.class);event.onLogin(userId);
}
构造方式
EventManager eventManager = new EventManager();
Map<String, Object> eventBeans = applicationContext.getBeansWithAnnotation(MessageService.class);
eventManager.init(eventBeans);
代码实现
https://download.csdn.net/download/qq_38746380/91888336