What is a mediator in Java?

Melody 105 Published: 08/11/2024

What is a mediator in Java?

I apologize for the confusion earlier!

In Java, a mediator is an object that acts as an intermediary between two or more objects in order to facilitate communication and coordination among them. The Mediator design pattern, also known as the "Command Pattern," allows you to decouple objects that would otherwise be tightly coupled, promoting loose coupling and better scalability.

To illustrate this concept, let's consider a simple example: a chat room with multiple users. In a traditional approach, each user would need to have direct references to all other users in order to send messages. This would result in a complex web of interdependencies between users. Instead, we can introduce a Mediator (the Chat Room) that handles the communication between users.

The Chat Room Mediator contains methods for sending and receiving messages, as well as maintaining a list of connected users. When a user sends a message, it gets sent to the Chat Room Mediator, which then broadcasts the message to all other connected users.

Here's a simplified representation of this design:

public interface User {

void receiveMessage(String message);

}

public class ChatRoom implements Mediator {

private List users = new ArrayList<>();

public void addUser(User user) {

users.add(user);

}

public void sendMessage(String message, User sender) {

for (User user : users) {

if (user != sender) {

user.receiveMessage(message);

}

}

}

}

public class ConcreteUser implements User {

private ChatRoom mediator;

public ConcreteUser(ChatRoom mediator) {

this.mediator = mediator;

mediator.addUser(this);

}

public void sendMessage(String message) {

mediator.sendMessage(message, this);

}

public void receiveMessage(String message) {

System.out.println("Received message: " + message);

}

}

By using a Mediator to coordinate communication between objects, you can:

Decouple objects that would otherwise be tightly coupled. Promote loose coupling and better scalability. Reduce the complexity of inter-object dependencies.

In summary, a mediator in Java is an object that acts as an intermediary between two or more objects to facilitate communication and coordination among them, allowing for loose coupling and improved scalability.

Java mediator example

Here's a detailed example of how to implement the Mediator design pattern in Java:

The Mediator pattern is used to reduce complex dependencies between objects and facilitate communication between them without having direct references. It's an alternative approach to traditional event-driven or callback-based systems.

Let's take a simple chat room application as an example, where multiple users can send and receive messages. We want to implement this functionality using the Mediator pattern.

Here's a simplified code example:

// The mediator interface

interface ChatRoom {

void sendMessage(String message);

}

class User extends Thread {

private String name;

private ChatRoom chatRoom;

public User(String name, ChatRoom chatRoom) {

this.name = name;

this.chatRoom = chatRoom;

}

public void run() {

for (int i = 0; i < 5; i++) {

String message = "Hello from user " + name;

chatRoom.sendMessage(message);

try {

Thread.sleep(1000); // Simulate a delay

} catch (InterruptedException e) {

System.out.println(e.getMessage());

}

}

}

}

// Concrete mediator class: Chat Room

class DefaultChatRoom implements ChatRoom {

private List users;

public DefaultChatRoom() {

this.users = new ArrayList<>();

}

@Override

public void sendMessage(String message) {

for (User user : users) {

user.interrupt(); // Send the message to each user

System.out.println("Sending message: " + message);

}

}

public void addUser(User user) {

this.users.add(user);

}

}

public class ChatRoomExample {

public static void main(String[] args) throws InterruptedException {

DefaultChatRoom chatRoom = new DefaultChatRoom();

for (int i = 0; i < 5; i++) {

User user = new User("User " + i, chatRoom);

user.start();

chatRoom.addUser(user);

}

Thread.sleep(10000); // Simulate a delay

}

}

In this example:

The ChatRoom interface defines the sendMessage method that sends a message to all registered users. The DefaultChatRoom class implements this interface and maintains a list of connected users. Each User class extends a thread, which represents a user sending messages in an infinite loop.

To reduce complexity:

Instead of having direct references between users (e.g., User A sending a message directly to User B), the Mediator pattern introduces an intermediate object (DefaultChatRoom) that facilitates communication. When a user sends a message, it doesn't need to know which other users are online or available. The mediator takes care of this and broadcasts the message to all connected users.

By implementing the Mediator design pattern in Java:

We decouple the User objects from each other, making them less dependent on one another. We simplify the code by avoiding direct references between users. We enable easy extensibility, as adding new types of messages or users can be done without affecting the existing logic.

This is just a simplified example, but the Mediator pattern has many practical applications in software development, such as event-driven systems, GUI components, and communication networks.