zl程序教程

您现在的位置是:首页 >  工具

当前栏目

Event Bus 设计模式学习笔记

2023-09-14 09:03:09 时间

原文:Design Patterns: Event Bus

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