WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Design Patterns · Expert · question 75 of 100

Explain how the Mediator pattern can be implemented using event-driven architectures and message brokers like RabbitMQ or Apache Kafka.?

📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by encapsulating their interactions within a mediator object. This reduces the dependencies between the objects, making the code more maintainable and scalable.

In an event-driven architecture, the Mediator pattern can be implemented using a message broker like RabbitMQ or Apache Kafka. When an event occurs, it is published to the broker, and the mediator subscribes to the relevant events. The mediator then processes the event, updating the relevant objects and publishing any changes back to the broker.

Here’s an example of how the Mediator pattern can be implemented using RabbitMQ in Java:

1. Create a mediator object that subscribes to relevant events on the RabbitMQ broker:

public class Mediator {
   private final Channel channel;

   public Mediator(Channel channel) {
      this.channel = channel;
      try {
         channel.exchangeDeclare("events", BuiltinExchangeType.TOPIC);
         String queueName = channel.queueDeclare().getQueue();
         channel.queueBind(queueName, "events", "user.*");
         channel.basicConsume(queueName, true, this::processEvent, consumerTag -> {});
      } catch (IOException e) {
         throw new RuntimeException("Failed to create mediator", e);
      }
   }

   private void processEvent(Delivery delivery) throws IOException {
      String routingKey = delivery.getEnvelope().getRoutingKey();
      byte[] body = delivery.getBody();

      // Parse the event and update the relevant objects
      Event event = parseEvent(body);
      if (routingKey.startsWith("user.")) {
         int userId = Integer.parseInt(routingKey.substring(5));
         updateUser(userId, event);
      }
   }

   private void updateUser(int userId, Event event) {
      // Update the user object with the event data
      User user = getUser(userId);
      user.update(event);

      // Publish any changes back to the broker
      try {
         byte[] data = serializeUser(user);
         channel.basicPublish("users", "user." + userId, null, data);
      } catch (IOException e) {
         throw new RuntimeException("Failed to publish user", e);
      }
   }
}

2. Create objects that subscribe to events on the mediator:

public class User {
   private final Mediator mediator;
   private final int id;
   // ...

   public User(Mediator mediator, int id) {
      this.mediator = mediator;
      this.id = id;
      mediator.subscribe("user." + id, this::onEvent);
   }

   private void onEvent(Event event) {
      // Handle the event
   }

   public void update(Event event) {
      // Update the user object with the event data
   }
}

3. Publish events to the RabbitMQ broker:

public class EventProducer {
   private final Channel channel;

   public EventProducer(Channel channel) {
      this.channel = channel;
      try {
         channel.exchangeDeclare("events", BuiltinExchangeType.TOPIC);
      } catch (IOException e) {
         throw new RuntimeException("Failed to create event producer", e);
      }
   }

   public void publish(Event event, String routingKey) {
      try {
         byte[] data = serializeEvent(event);
         channel.basicPublish("events", routingKey, null, data);
      } catch (IOException e) {
         throw new RuntimeException("Failed to publish event", e);
      }
   }
}

With this implementation, objects can communicate with each other indirectly through the mediator, reducing the coupling between them. Any changes to the objects are propagated through the mediator and published back to the broker, ensuring consistency across the system.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Design Patterns interview — then scores it.
📞 Practice Design Patterns — free 15 min
📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

All 100 Design Patterns questions · All topics