DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Design Event Streams, Part 3
  • How to Design Event Streams, Part 1
  • Art Of Knowledge Crunching In Domain Driven Design
  • Evolutionary Architecture: A Solution to the Lost Art of Software Design

Trending

  • AI’s Role in Everyday Development
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Design Patterns: Event Bus

Design Patterns: Event Bus

Want to learn more about the Event Bus design pattern? Click here to check out example code for your projects.

By 
Mehdi Cheracher user avatar
Mehdi Cheracher
·
Nov. 08, 18 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
125.2K Views

Join the DZone community and get the full member experience.

Join For Free

Today, we are tackling something that is kind of new (and by that, I mean not mentioned in the GoF book), and that is the Event Bus.

Motivation

Imagine having a large scale application containing a lot of components interacting with each other, and you want a way to make your components communicate while maintaining loose coupling and separation of concerns principles, the Event Bus pattern can be a good solution for your problem.

The idea of an Event bus is actually quite similar to the Bus studied in Networking (Bus Topology). You have some kind of pipeline and computers connected to it, and whenever one of them sends a message, it’s dispatched to all of the others. Then, they decide if they want to consume the given message or just discard it.

Bus Networking Topology

At a component level, it’s quite similar: the computers are your application components, the message is the event or the data you want to communicate, and the pipeline is your EventBus object.

Implementation

There is no “correct” way to implement an Event Bus. I'm going to give a peak at two approaches here, finding other approaches is left as an exercise to the reader.

First Pattern

This one is kind of classic, as it relays on defining your EventBus interface (to force a given contract), implementing it the way you want, and defining a  Subscribable (another contract) to handle the Event(and yet another contract) consumption.

/**
 * 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
 *
 * @author chermehdi
 */
public interface Event<T> {

  /**
   * @returns the stored data associated with the event
   */
  T getData();
}


import java.util.Set;

/**
 * Description of a generic subscriber
 *
 * @author chermehdi
 */
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
 *
 * @author chermehdi
 */
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();
}


The Subscribable declares a method to handle a given type of objects and what type of objects it supports by defining the supports method .

The EventBus implementation holds a List of all the Subscribables and notifies all of them each time a new event comes to the  EventBusdispatch method .

Opting for this solution gives you compile time that checks the passed Subscribables, and also, it’s the more OO way of doing it, with no reflection magic needed, and as you can see, it can be easy to implement. The downside is that contract forcing thing — you always need a new class to handle a type of event, which might not be a problem at first, but as your project grows, you’re going to find it a little bit repetitive to create a class just to handle simple logic, such as logging or statistics.

Second Pattern

This pattern is inspired from Guava’s implementation, the EventBus implementation looks much simpler and easier to use. For every event consumer, you can just annotate a given method with @Subscribe and pass it an object of the type you want to consume (a single object/parameter), and you can register it as a message consumer by just calling eventBus.register(objectContainingTheMethod). To produce a new event, all you have to do is call eventBus.post(SomeObject) and all the interested consumers will be notified.

What happens if no consumer is found for a given object? Well, nothing really. In guava’s implementation, they call them DeadEvents; in my implementation, the call to post is just ignored .

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Simple implementation demonstrating how a guava EventBus works generally, without all the noise
 * of special cases handling, and special guava collections
 *
 * @author chermehdi
 */
public class EventBus {

  private Map<Class<?>, List<Invocation>> invocations;

  private String name;

  public EventBus(String name) {
    this.name = name;
    invocations = new ConcurrentHashMap<>();
  }

  public void post(Object object) {
    Class<?> clazz = object.getClass();
    if (invocations.containsKey(clazz)) {
      invocations.get(clazz).forEach(invocation -> invocation.invoke(object));
    }
  }

  public void register(Object object) {
    Class<?> currentClass = object.getClass();
    // we try to navigate the object tree back to object ot see if
    // there is any annotated @Subscribe classes
    while (currentClass != null) {
      List<Method> subscribeMethods = findSubscriptionMethods(currentClass);
      for (Method method : subscribeMethods) {
        // we know for sure that it has only one parameter
        Class<?> type = method.getParameterTypes()[0];
        if (invocations.containsKey(type)) {
          invocations.get(type).add(new Invocation(method, object));
        } else {
          List<Invocation> temp = new Vector<>();
          temp.add(new Invocation(method, object));
          invocations.put(type, temp);
        }
      }
      currentClass = currentClass.getSuperclass();
    }
  }

  private List<Method> findSubscriptionMethods(Class<?> type) {
    List<Method> subscribeMethods = Arrays.stream(type.getDeclaredMethods())
        .filter(method -> method.isAnnotationPresent(Subscribe.class))
        .collect(Collectors.toList());
    checkSubscriberMethods(subscribeMethods);
    return subscribeMethods;
  }

  private void checkSubscriberMethods(List<Method> subscribeMethods) {
    boolean hasMoreThanOneParameter = subscribeMethods.stream()
        .anyMatch(method -> method.getParameterCount() != 1);
    if (hasMoreThanOneParameter) {
      throw new IllegalArgumentException(
          "Method annotated with @Susbscribe has more than one parameter");
    }
  }

  public Map<Class<?>, List<Invocation>> getInvocations() {
    return invocations;
  }

  public String getName() {
    return name;
  }
}


You can see that opting for this solution requires less work on your part — nothing prevents you from naming your handler methods intention-revealing names rather than a general handle. And, you can define all your consumers on the same class. You just need to pass a different event type for each method.

Conclusion

Implementing an EventBus pattern can be beneficial for your code base as it helps loose coupling your classes and promotes a publish-subscribe pattern. It also help components interact without being aware of each other. Whichever implementation you choose to follow is a matter of taste and requirements.

All the code samples and implementation can be found in this repo.

Event Loose coupling Design

Published at DZone with permission of Mehdi Cheracher. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Design Event Streams, Part 3
  • How to Design Event Streams, Part 1
  • Art Of Knowledge Crunching In Domain Driven Design
  • Evolutionary Architecture: A Solution to the Lost Art of Software Design

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!