前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Event Bus 设计模式学习笔记

Event Bus 设计模式学习笔记

作者头像
Jerry Wang
发布2021-10-21 10:36:03
3470
发布2021-10-21 10:36:03
举报

原文:Design Patterns: Event Bus

Motivation

想象一下,有一个包含大量相互交互的组件的大型应用程序,并且您想要一种方法使您的组件进行通信,同时保持松散耦合和关注点分离原则,事件总线模式可以很好地解决您的问题。

事件总线的想法实际上与网络(总线拓扑)中研究的总线非常相似。 你有某种管道和连接到它的计算机,每当其中一个发送消息时,它就会被分派给所有其他人。 然后,他们决定是要使用给定的消息还是只是丢弃它。

在组件级别,它非常相似:计算机是您的应用程序组件,消息是您要通信的事件或数据,管道是您的 EventBus 对象。

下面是一种经典的实现方式,因为它依赖于定义您的 EventBus 接口(强制给定的合约),以您想要的方式实现它,并定义一个 Subscribable(另一个合约)来处理 Event(和另一个合约)消费。

定义一个事件接口:

代码语言:javascript
复制
/**
 * 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();
}

定义事件的监听者即事件消费者:

代码语言:javascript
复制
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();
}

事件总线的实现:

代码语言:javascript
复制
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,而且,这是一种更面向对象的方式,不需要反射魔法,而且如您所见,它很容易实现。 缺点是契约强制的事情——你总是需要一个新的类来处理一种类型的事件,一开始这可能不是问题,但随着你的项目的增长,你会发现创建一个有点重复 类只是处理简单的逻辑,例如日志记录或统计信息。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-09-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Motivation
相关产品与服务
事件总线
腾讯云事件总线(EventBridge)是一款安全,稳定,高效的云上事件连接器,作为流数据和事件的自动收集、处理、分发管道,通过可视化的配置,实现事件源(例如:Kafka,审计,数据库等)和目标对象(例如:CLS,SCF等)的快速连接,当前 EventBridge 已接入 100+ 云上服务,助力分布式事件驱动架构的快速构建。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档