Implementing an event bus with the Singleton and Observer patterns
A message bus is an implementation of the Observer pattern that we saw in Chapter 2, Software Design Principles and Patterns. As a short refreshment of the main concept, we seek to create an object or structure that receives and emits events that our components can subscribe and react to. This pattern runs independently of the component tree structure, so any component and service can make use of it. Visually, we can represent the resulting relationship as follows:
Figure 7.2 – A simplified view of a message bus relationship with components
From the preceding diagram, we can immediately see that each component is treated equally by the message bus. Each component subscribes one or more of its methods to a specific event, and at the same time has the same possibility to publish an event. This makes it very flexible, as events can also transport data.
Let’s bring down to...