概述
中介者模式是一种行为设计模式,它通过引入一个中介角色来封装多个对象之间的交互关系,从而降低这些对象之间的耦合度。这种模式让对象之间不需要显式地相互引用,而是通过中介者进行间接通信,这有利于系统的解耦、扩展和维护。
目的
减少耦合:中介者模式使得各个同事(Colleague)对象不需要直接相互依赖,减少了系统的复杂性。
集中控制:通过中介者统一管理对象间的交互,可以更容易地控制和协调这些交互,便于维护和扩展系统。
灵活性:新增或移除同事类对其他对象的影响减小,系统更易于扩展和重构。
角色
Mediator(中介者):定义一个接口,用于同事对象之间的通信。
ConcreteMediator(具体中介者):实现中介者接口,负责协调各同事对象的行为,实现它们之间的协作。
Colleague(同事):定义同事类接口,保存对中介者的引用,可以通过中介者与其他同事通信。
ConcreteColleague(具体同事):实现同事接口,实现自己的业务逻辑,并在需要与其他同事通信时,通过中介者完成。
适用场景
系统中对象之间存在复杂的网状结构,每个对象都与其他多个对象有直接关联,导致难以理解和维护。
需要对一个对象结构中的对象之间的通信进行集中控制,以避免相互依赖带来的复杂性。
希望可以独立改变同事类和中介者类,而不会影响到其他部分的代码。
实现步骤
定义中介者接口:声明一个接口,定义同事对象之间的通信方法。
创建具体中介者类:实现中介者接口,处理并协调各同事对象的请求。
定义同事接口:声明一个接口,用于接收来自中介者的消息。
创建具体同事类:实现同事接口,通过中介者与其他同事通信。
在具体同事类中引入中介者:同事类不再直接与其他同事通信,而是通过中介者转发消息。
代码示例
中介者接口
public interface Mediator {
void send(String message, Colleague colleague);
}
具体中介者类
public class ConcreteMediator implements Mediator {
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public void setColleague1(ConcreteColleague1 colleague1) {
this.colleague1 = colleague1;
}
public void setColleague2(ConcreteColleague2 colleague2) {
this.colleague2 = colleague2;
}
@Override
public void send(String message, Colleague colleague) {
if (colleague == colleague1) {
colleague2.receive(message);
} else {
colleague1.receive(message);
}
}
}
同事接口
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
}
具体同事类
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
public void send(String message) {
mediator.send(message, this);
}
public void receive(String message) {
System.out.println("ConcreteColleague1 received: " + message);
}
}
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
public void send(String message) {
mediator.send(message, this);
}
public void receive(String message) {
System.out.println("ConcreteColleague2 received: " + message);
}
}
总结
中介者模式通过引入中介者对象来封装对象间的复杂交互,降低了系统的耦合度,提高了系统的灵活性和可维护性。适用于那些对象间交互复杂且频繁变化的场景,但需注意,过度使用可能导致中介者本身变得过于复杂,成为系统中的另一个瓶颈。正确识别并应用中介者模式,可以在设计中有效平衡对象间的依赖关系。
评论区