Welcome to our deep dive into the Mediator Pattern in Java! This tutorial is designed to help both beginners and intermediates understand and apply this design pattern in their projects.
The Mediator Pattern is a behavioral design pattern that simplifies communication and reduces dependencies between classes in a system. It acts as an intermediary, allowing objects to communicate without a direct reference to each other.
A mediator is an object that manages communication between other objects, often called colleagues. Here's a simple example:
// Colleague classes
class ConcreteColleagueA {
// ...
void send(String message, Mediator mediator) {
mediator.send(message, this);
}
// ...
}
class ConcreteColleagueB {
// ...
void receive(String message, Colleague sender) {
// handle message
}
// ...
}
// Mediator interface
interface Mediator {
void send(String message, Colleague colleague);
void register(Colleague colleague);
}In this example, ConcreteColleagueA and ConcreteColleagueB are the colleague classes that communicate through the Mediator interface.
Let's consider a simple chat room scenario. Each user (User) in the chat room can send and receive messages. However, we don't want users to have direct access to each other, to avoid direct communication and maintain privacy. Instead, we create a ChatRoom mediator that handles all the communication:
// User class
class User {
private String name;
private ChatRoom chatRoom;
public User(String name) {
this.name = name;
}
public void setChatRoom(ChatRoom chatRoom) {
this.chatRoom = chatRoom;
chatRoom.register(this);
}
public void sendMessage(String message) {
chatRoom.sendMessage(message, this);
}
public void receiveMessage(String message, User sender) {
System.out.printf("%s: %s\n", sender.getName(), message);
}
public String getName() {
return name;
}
}
// ChatRoom class
class ChatRoom implements Mediator {
private List<User> users;
public ChatRoom() {
users = new ArrayList<>();
}
public void register(User user) {
users.add(user);
}
public void sendMessage(String message, User sender) {
for (User user : users) {
if (user != sender) {
user.receiveMessage(message, sender);
}
}
}
}In this example, each user (User) can send messages (sendMessage) and receive messages (receiveMessage). The ChatRoom mediator manages the communication between users, ensuring they can't directly access each other.
In the Mediator Pattern, what is the role of the Mediator object?
With this lesson, you've learned the basics of the Mediator Pattern in Java. Apply these concepts to simplify communication in your projects and make your code more maintainable! 💡