中介者模式(Mediator Pattern)是一种设计模式,它用于减少类之间的直接依赖,通过引入一个中介者类来协调它们之间的交互。在Java聊天室系统中,中介者模式可以应用于处理用户之间的消息传递、房间管理以及用户与系统的交互等场景。
以下是在Java聊天室系统中应用中介者模式的一个简单示例:
public interface Mediator {
void sendMessage(User sender, User receiver, String message);
void sendNotification(User user, String notification);
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChatRoomMediator implements Mediator {
private Map<User, List<User>> roomMap = new HashMap<>();
private List<User> users = new ArrayList<>();
@Override
public void sendMessage(User sender, User receiver, String message) {
// 检查接收者是否在线
if (!users.contains(receiver)) {
sendNotification(receiver, "You have been added to the chat room.");
}
// 将消息发送到接收者的房间
List<User> receivers = roomMap.getOrDefault(receiver, new ArrayList<>());
receivers.add(sender);
// 通知房间内的所有用户有新消息
for (User user : receivers) {
sendNotification(user, sender.getName() + ": " + message);
}
}
@Override
public void sendNotification(User user, String notification) {
System.out.println(notification + " to " + user.getName());
}
public void addUser(User user) {
users.add(user);
roomMap.putIfAbsent(user, new ArrayList<>());
}
public void removeUser(User user) {
users.remove(user);
for (List<User> receivers : roomMap.values()) {
receivers.remove(user);
}
roomMap.remove(user);
}
}
public class User {
private String name;
private Mediator mediator;
public User(String name, Mediator mediator) {
this.name = name;
this.mediator = mediator;
}
public String getName() {
return name;
}
public void sendMessage(User receiver, String message) {
mediator.sendMessage(this, receiver, message);
}
public void receiveNotification(String notification) {
mediator.sendNotification(this, notification);
}
}
public class ChatRoomSystem {
public static void main(String[] args) {
Mediator mediator = new ChatRoomMediator();
User user1 = new User("Alice", mediator);
User user2 = new User("Bob", mediator);
User user3 = new User("Charlie", mediator);
mediator.addUser(user1);
mediator.addUser(user2);
mediator.addUser(user3);
user1.sendMessage(user2, "Hello, Bob!");
user1.sendMessage(user3, "Hi, Charlie!");
}
}
在这个示例中,我们使用中介者模式来处理用户之间的消息传递和通知。通过将用户之间的直接通信转换为通过中介者的间接通信,我们可以更容易地管理用户之间的关系和通信逻辑。此外,中介者模式还可以用于处理更复杂的场景,例如房间管理、用户加入和离开等。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。