Java 4 min read

The Mediator Design Pattern: Centralize Complex Communications

Master the Mediator Pattern in Java. Learn how to reduce coupling by having objects communicate through a mediator instead of directly.

MR

Moshiour Rahman

Advertisement

The Problem: Spaghetti Communication

Imagine a chat application with 5 users. If everyone talks directly to everyone:

  • User A → User B, C, D, E
  • User B → User A, C, D, E

That’s N × (N-1) = 20 connections for 5 users!
For 100 users: 9,900 connections 💥

Each user needs to know about all other users. Adding/removing users breaks everything.

The Solution: The Mediator Pattern

The Mediator Pattern encapsulates how objects interact. Objects don’t communicate directly; they go through a mediator.

Real-Life Analogy: Air Traffic Control 🛫

Without mediator:
Pilots talk to each other directly:

  • “Flight 101 to all planes: I’m landing on runway 3”
  • “Flight 202 to all planes: I’m taking off from runway 5”

Chaos! Missed messages, collisions.

With mediator (ATC tower):

  • Pilot → Tower: “Request landing”
  • Tower → Pilot: “Cleared for runway 3”
  • Tower coordinates all planes

Visualizing the Pattern

Mediator Pattern

Implementation

1. The Mediator Interface

public interface ChatMediator {
    void sendMessage(String message, User sender);
    void addUser(User user);
}

2. Concrete Mediator

import java.util.ArrayList;
import java.util.List;

public class ChatRoom implements ChatMediator {
    private List<User> users = new ArrayList<>();

    @Override
    public void addUser(User user) {
        users.add(user);
    }

    @Override
    public void sendMessage(String message, User sender) {
        // Broadcast to all except sender
        for (User user : users) {
            if (user != sender) {
                user.receive(message);
            }
        }
    }
}

3. Colleague (User)

public class User {
    private String name;
    private ChatMediator mediator;

    public User(String name, ChatMediator mediator) {
        this.name = name;
        this.mediator = mediator;
    }

    public void send(String message) {
        System.out.println(name + " sends: " + message);
        mediator.sendMessage(message, this); // Delegate to mediator
    }

    public void receive(String message) {
        System.out.println(name + " received: " + message);
    }
}

Usage

ChatMediator chatRoom = new ChatRoom();

User alice = new User("Alice", chatRoom);
User bob = new User("Bob", chatRoom);
User charlie = new User("Charlie", chatRoom);

chatRoom.addUser(alice);
chatRoom.addUser(bob);
chatRoom.addUser(charlie);

alice.send("Hello everyone!");
// Output:
// Alice sends: Hello everyone!
// Bob received: Hello everyone!
// Charlie received: Hello everyone!

bob.send("Hi Alice!");
// Alice received: Hi Alice!
// Charlie received: Hi Alice!

Mediator vs Observer

PatternCommunicationUse When
MediatorTwo-way coordination between colleaguesComplex interactions between objects
ObserverOne-way notifications (Subject → Observers)One object needs to notify many

In The Wild (Real World Examples)

1. Java Swing Event Handling

JFrame acts as a mediator between components:

JButton button = new JButton("Click");
JTextField field = new JTextField();

button.addActionListener(e -> {
    // Mediator coordinates interaction
    field.setText("Button clicked");
});

2. Spring ApplicationEventPublisher

Spring’s event mechanism is a mediator:

@Service
public class OrderService {
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public void createOrder(Order order) {
        // ... save order...
        eventPublisher.publishEvent(new OrderCreatedEvent(order));
        // Mediator notifies all listeners
    }
}

3. MVC Controller

The Controller is a mediator between Model and View:

@Controller
public class UserController {
    // Mediates between UserService (model) and templates (view)
    @GetMapping("/users")
    public String getUsers(Model model) {
        model.addAttribute("users", userService.findAll());
        return "users"; // View coordinated by mediator
    }
}

Cheat Sheet

FeatureDetails
CategoryBehavioral
Problem SolvedTight coupling from many-to-many object interactions
Key implementationCentral mediator object coordinates all interactions
ProsDecoupling (objects don’t know about each other), Reusability
ConsGod Object risk (mediator can become too complex)

Tips to Remember 🧠

  • “ATC Tower”: Planes (objects) talk to tower (mediator), not each other.
  • “Spaghetti Buster”: Turns N-to-N connections into N-to-1.
  • “MVC”: Controller is a classic mediator example.

Advertisement

MR

Moshiour Rahman

Software Architect & AI Engineer

Share:
MR

Moshiour Rahman

Software Architect & AI Engineer

Enterprise software architect with deep expertise in financial systems, distributed architecture, and AI-powered applications. Building large-scale systems at Fortune 500 companies. Specializing in LLM orchestration, multi-agent systems, and cloud-native solutions. I share battle-tested patterns from real enterprise projects.

Related Articles

Comments

Comments are powered by GitHub Discussions.

Configure Giscus at giscus.app to enable comments.