中介者模式(Mediator Pattern)是一种行为型设计模式,它通过封装一系列对象之间的交互方式,使这些对象能够互相通信而不需要直接相互引用。中介者模式通过集中控制对象的交互,使得对象之间的耦合度降低,同时也提高了系统的可维护性和可扩展性。
优点:
缺点:
使用场景:
假设有一个聊天室系统,其中包含多个用户,用户之间可以发送消息进行交流。用户之间的通信交互较为复杂,每个用户都需要了解其他用户的情况。这时可以使用中介者模式来解决。
首先,定义中介者接口ChatMediator
,并在接口中定义发送消息的方法:
public interface ChatMediator {
void sendMessage(String message, User user);
}
然后,实现具体的中介者类ChatRoom
,负责协调用户之间的通信:
import java.util.ArrayList;
import java.util.List;
public class ChatRoom implements ChatMediator {
private List users;
public ChatRoom() {
this.users = new ArrayList<>();
}
@Override
public void sendMessage(String message, User user) {
for (User u : users) {
if (u != user) {
u.receiveMessage(message);
}
}
}
public void addUser(User user) {
users.add(user);
}
}
接下来,定义用户接口User
,并在接口中定义发送和接收消息的方法:
public interface User {
void sendMessage(String message);
void receiveMessage(String message);
}
然后,实现具体的用户类ChatUser
,负责实现用户接口,并在实现类中保存中介者的引用:
public class ChatUser implements User {
private ChatMediator chatMediator;
private String name;
public ChatUser(ChatMediator chatMediator, String name) {
this.chatMediator = chatMediator;
this.name = name;
}
@Override
public void sendMessage(String message) {
chatMediator.sendMessage(message, this);
}
@Override
public void receiveMessage(String message) {
System.out.println(name + " received message: " + message);
}
}
最后,我们可以创建聊天室对象和多个用户对象,并让用户之间通过聊天室发送和接收消息:
public class MediatorExample {
public static void main(String[] args) {
// 创建聊天室对象
ChatRoom chatRoom = new ChatRoom();
// 创建用户对象
User user1 = new ChatUser(chatRoom, "User1");
User user2 = new ChatUser(chatRoom, "User2");
User user3 = new ChatUser(chatRoom, "User3");
// 添加用户到聊天室
chatRoom.addUser(user1);
chatRoom.addUser(user2);
chatRoom.addUser(user3);
// 用户发送消息
user1.sendMessage("Hello, everyone!");
user2.sendMessage("Hi, User1!");
user3.sendMessage("Nice to meet you all!");
}
}
运行结果
User2 received message: Hello, everyone!
User3 received message: Hello, everyone!
User1 received message: Hi, User1!
User3 received message: Hi, User1!
User1 received message: Nice to meet you all!
User2 received message: Nice to meet you all!