中介者模式的核心逻辑就是解耦对象‘多对多’的相互依赖关系。当遇到一大堆混乱的对象呈现“网状结构”,利用通过中介者模式解耦对象之间的通讯。
代码案例
抽象中介类
public abstract class AbstractChatRoom {
public abstract void notice(String message , User user); //声明notice方法
public abstract void register(User user);
}
实现中介类
package com.example.dyc.mymedia;
import java.util.ArrayList;
import java.util.List;
public class ChatRoom extends AbstractChatRoom { //继承AbstractChatRoom
public List<User> users = new ArrayList<>(); //声明列表类存储User
@Override
public void register(User user){ //登录添加用户
users.add(user);
}
@Override
public void notice(String message,User user){ //notice方法的重写
for(User u : users){ //遍历
if(u != user){
u.getMessage(message);
}
}
}
}
User
package com.example.dyc.mymedia;
public abstract class User { //抽象类
protected AbstractChatRoom chatRoom; //聊天室对象
public User(AbstractChatRoom chatRoom){
this.chatRoom = chatRoom;
this.chatRoom.register(this);
}
public abstract void sendMessage(String msg); //声明发送消息的方法
public abstract void getMessage(String msg); //声明接收消息的方法
}
UserA:
package com.example.dyc.mymedia;
//UserA
public class UserA extends User {
private String userId;
public UserA(String userId, AbstractChatRoom chatRoom) {
super(chatRoom);
this.userId = userId;
}
@Override
public void sendMessage(String msg){
System.out.println(userId + "发送 "+msg);
chatRoom.notice(msg,this);
}
@Override
public void getMessage(String msg){
System.out.println(userId + "收到 "+msg );
}
}
客户端
public class MyTest {
public static void main(String[] args) {
ChatRoom chatRoom = new ChatRoom();
UserA userLi = new UserA("小李", chatRoom);
UserA userWa = new UserA("小娃", chatRoom);
userLi.sendMessage("我是小李");
System.out.println("===================");
userWa.sendMessage("我是小娃");
}
}
参考资料:
Java-设计模式(中介模式实现聊天室)_使用设计模式实现聊天室要求真实实现-CSDN博客