Event Bus 设计模式学习笔记
原文: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,而且,這是一種更面向對象的方式,不需要反射魔法,而且如您所見,它很容易實現。 缺點是契約強制的事情——你總是需要一個新的類來處理一種類型的事件,一開始這可能不是問題,但隨著你的項目的增長,你會發現創建一個有點重復 類只是處理簡單的邏輯,例如日志記錄或統計信息。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Event Bus 设计模式学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 买一得四:芒果 TV 会员年卡 3 折
- 下一篇: 上汽集团 4 月新能源汽车销量 6.8