Behavioral Design Pattern · Java

Mediator Design Pattern in Java

Centralize communication between related objects through a mediator.

What is Mediator?

Instead of every component knowing every other component, each component talks to the mediator. This reduces many-to-many dependencies.

Beginner-friendly Java example

Focus on the roles in the example first. The pattern becomes easier when you can identify the sender, receiver, context, state, or strategy involved.

class ChatRoom {
    void send(String message, User sender) {
        System.out.println(sender.name() + ": " + message);
    }
}

record User(String name, ChatRoom room) {
    void send(String message) {
        room.send(message, this);
    }
}

ChatRoom room = new ChatRoom();
new User("Asha", room).send("Hello team");

Benefits and trade-offs

Benefits
  • Keeps responsibilities focused.
  • Reduces conditional and tightly coupled code.
  • Makes behavior easier to extend and test.
Trade-offs
  • Can introduce extra objects and interfaces.
  • Too many small classes can make simple logic harder to follow.

Real-time use cases

  • Chat rooms
  • Air traffic coordination
  • UI component communication
  • Order workflow coordination
Key takeawayCentralize communication between related objects through a mediator. Use it when behavior or communication is changing faster than the objects themselves.