Mediator(中介者模式)
介绍
中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性,用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式属于行为型模式。
优点:
- 降低了类的复杂度,将一对多转化成了一对一
- 各个类之间的解耦
- 符合迪米特原则
缺点: 中介者会庞大,变得复杂难以维护
实现

1、创建聊天室
public class ChatRoom {
public static void sendMessage(User user, String message) {
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
+ "[" + user.getName() + "]:" + message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2、创建User
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User (String name) {
this.name = name;
}
public void sendMessage(String message) {
ChatRoom.sendMessage(this, message);
}
}
3、 使用 User 对象来进行他们之间的通信。
public class MediatorDemo {
public static void main(String[] args) {
User jack = new User("Jack");
User lucy = new User("Lucy");
jack.sendMessage("Hello Lucy, I am Jack");
lucy.sendMessage("Hi Jack , I am Lucy");
}
}
中介者模式是一种行为设计模式,通过引入一个中介对象,减少多个对象间的直接交互,降低了系统的耦合度。在示例中,ChatRoom作为中介,使得User对象能够互相发送消息,而无需知道其他用户的存在。这种模式的优点在于提高了代码的可维护性,但可能导致中介者自身变得复杂。
1926

被折叠的 条评论
为什么被折叠?



