The Mediator Pattern consists of three main components:
The main idea behind the Mediator Pattern is to reduce the direct dependencies between objects. By using a mediator, the objects can be more independent and easier to maintain.
// Mediator interface
interface ChatMediator {
void sendMessage(String message, User user);
void addUser(User user);
}
// Colleague interface
interface User {
void receiveMessage(String message);
void sendMessage(String message);
}
import java.util.ArrayList;
import java.util.List;
// Concrete Mediator
class ChatMediatorImpl implements ChatMediator {
private List<User> users;
public ChatMediatorImpl() {
this.users = new ArrayList<>();
}
@Override
public void sendMessage(String message, User user) {
for (User u : users) {
if (u != user) {
u.receiveMessage(message);
}
}
}
@Override
public void addUser(User user) {
this.users.add(user);
}
}
// Concrete Colleague
class UserImpl implements User {
private String name;
private ChatMediator mediator;
public UserImpl(String name, ChatMediator mediator) {
this.name = name;
this.mediator = mediator;
}
@Override
public void receiveMessage(String message) {
System.out.println(name + " received: " + message);
}
@Override
public void sendMessage(String message) {
System.out.println(name + " sent: " + message);
mediator.sendMessage(message, this);
}
}
public class MediatorPatternExample {
public static void main(String[] args) {
ChatMediator mediator = new ChatMediatorImpl();
User user1 = new UserImpl("Alice", mediator);
User user2 = new UserImpl("Bob", mediator);
User user3 = new UserImpl("Charlie", mediator);
mediator.addUser(user1);
mediator.addUser(user2);
mediator.addUser(user3);
user1.sendMessage("Hello, everyone!");
}
}
In this example, we have a simple chat application. The ChatMediator
acts as the mediator, and the User
objects are the colleagues. When a user sends a message, it is sent to the mediator, and the mediator then distributes the message to all other users.
The Mediator Pattern is a powerful design pattern that can significantly improve the maintainability and scalability of your Java applications. By centralizing the communication between objects, it reduces the direct dependencies and makes the system more modular. In this blog post, we have explored the fundamental concepts, usage methods, common practices, and best practices of the Mediator Pattern in Java. By following these guidelines, you can effectively use the Mediator Pattern in your projects.