Event Bus 设计模式学习笔记
2023-09-14 09:03:09 时间
Motivation
想象一下,有一个包含大量相互交互的组件的大型应用程序,并且您想要一种方法使您的组件进行通信,同时保持松散耦合和关注点分离原则,事件总线模式可以很好地解决您的问题。
事件总线的想法实际上与网络(总线拓扑)中研究的总线非常相似。 你有某种管道和连接到它的计算机,每当其中一个发送消息时,它就会被分派给所有其他人。 然后,他们决定是要使用给定的消息还是只是丢弃它。
在组件级别,它非常相似:计算机是您的应用程序组件,消息是您要通信的事件或数据,管道是您的 EventBus 对象。
下面是一种经典的实现方式,因为它依赖于定义您的 EventBus 接口(强制给定的合约),以您想要的方式实现它,并定义一个 Subscribable(另一个合约)来处理 Event(和另一个合约)消费。
定义一个事件接口:
/**
* interface describing a generic event, and it's associated meta data, it's this what's going to
* get sent in the bus to be dispatched to intrested Subscribers
*/
public interface Event<T> {
/**
* @returns the stored data associated with the event
*/
T getData();
}
定义事件的监听者即事件消费者:
import java.util.Set;
/**
* Description of a generic subscriber
*/
public interface Subscribable {
/**
* Consume the events dispatched by the bus, events passed as parameter are can only be of type
* declared by the supports() Set
*/
void handle(Event<?> event);
/**
* describes the set of classes the subscribable object intends to handle
*/
Set<Class<?>> supports();
}
事件总线的实现:
import java.util.List;
/**
* Description of the contract of a generic EventBus implementation, the library contains two main
* version, Sync and Async event bus implementations, if you want to provide your own implementation
* and stay compliant with the components of the library just implement this contract
*/
public interface EventBus {
/**
* registers a new subscribable to this EventBus instance
*/
void register(Subscribable subscribable);
/**
* send the given event in this EventBus implementation to be consumed by interested subscribers
*/
void dispatch(Event<?> event);
/**
* get the list of all the subscribers associated with this EventBus instance
*/
List<Subscribable> getSubscribers();
}
Subscribable 通过定义 supports 方法声明了一种方法来处理给定类型的对象以及它支持的对象类型。
EventBus 实现持有所有 Subscribables 的列表,并在每次有新事件进入 EventBusdispatch 方法时通知所有订阅者。
选择此解决方案可为您提供编译时间来检查传递的 Subscribables,而且,这是一种更面向对象的方式,不需要反射魔法,而且如您所见,它很容易实现。 缺点是契约强制的事情——你总是需要一个新的类来处理一种类型的事件,一开始这可能不是问题,但随着你的项目的增长,你会发现创建一个有点重复 类只是处理简单的逻辑,例如日志记录或统计信息。
相关文章
- LeetCode笔记:Biweekly Contest 86
- MyBatis 源码学习笔记(二)- MyBatis 进阶(Part B)
- 【机器学习笔记】有监督学习和无监督学习
- 计算机三级嵌入式学习笔记(一)
- 操作系统概念 学习笔记
- 《简单记个笔记》之部分CSS选择器介绍
- C语言指针基础知识【C语言学习笔记】
- 【设计模式】学习笔记(一)——基本概念和设计原则
- 【设计模式】学习笔记(三)——结构型设计模式
- GDC 笔记 - FidelityFX Super Resolution 2.0
- 网络编程学习笔记1
- Pytest学习笔记7——接口自动化测试框架实战附源码(开荒篇)
- Spring AOP 笔记 简单易解
- Servlet学习笔记4(request请求对象、response响应对象1)
- 【Android 应用开发】Android 网络编程 API笔记 - java.net 包 权限 地址 套接字 相关类 简介
- KgCaptcha验证码实现笔记
- Linux防火墙iptables学习笔记(四)iptables实现NAT
- 25个字太短无法表达,以下是几个选择:1. Oracle学习笔记:我的经验分享 2. Oracle笔记:快速成为数据库专家 3. Oracle学习笔记:从入门到精通 4. Oracle数据库笔记:提高工作效率的方法 5. Oracle笔记:解决常见问题的技巧(oracle笔记)
- APACHE安装笔记
- PHP学习笔记之三数据库基本操作
- javascript学习笔记(九)js对象设计模式
- CentOS6.3编译安装LAMP环境笔记