中介者模式:协调对象交互,提升设计灵活性
2024-01-28 05:11:03
中介者模式的优点
-
降低耦合度:中介者模式通过引入中介对象,将对象之间的直接依赖关系转为依赖于中介对象,从而降低了对象之间的耦合度。这使得对象之间更加独立,便于维护和扩展。
-
提高灵活性:中介者模式将对象之间的交互封装在中介对象中,使得对象之间可以独立地改变其交互方式。这提高了系统的灵活性,便于应对需求的变化。
-
简化沟通:中介者模式通过将对象之间的沟通集中在中介对象中,简化了对象之间的沟通过程。这使得系统更加容易理解和维护。
中介者模式的应用场景
-
多个对象之间存在复杂的交互关系:当多个对象之间存在复杂的交互关系时,可以使用中介者模式来协调这些对象之间的交互,避免对象之间直接耦合。
-
需要隔离对象之间的变化:当需要隔离对象之间的变化时,可以使用中介者模式来封装对象之间的交互。这样,当一个对象发生变化时,不会影响到其他对象。
-
需要集中控制对象之间的交互:当需要集中控制对象之间的交互时,可以使用中介者模式来实现这一点。中介者对象可以根据需要来控制对象之间的交互,从而实现对系统行为的集中控制。
中介者模式的实现
中介者模式的实现可以分为以下几个步骤:
-
定义中介者接口:定义一个中介者接口,该接口包含了中介者对象需要实现的方法。
-
定义具体中介者类:定义一个或多个具体中介者类,实现中介者接口的方法。
-
定义同事类:定义同事类,同事类是与中介者对象交互的对象。
-
将同事类与中介者对象关联:将同事类与中介者对象关联起来,同事类可以通过中介者对象来与其他同事类交互。
中介者模式的示例
以下是一个使用中介者模式的示例:
class Mediator {
public void send(String message, Colleague colleague) {
// 将消息发送给其他同事
}
}
class Colleague {
private Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public void send(String message) {
// 通过中介者发送消息
mediator.send(message, this);
}
public void receive(String message) {
// 从中介者接收消息
}
}
class ConcreteMediator extends Mediator {
private List<Colleague> colleagues = new ArrayList<>();
public void addColleague(Colleague colleague) {
colleagues.add(colleague);
}
@Override
public void send(String message, Colleague colleague) {
for (Colleague c : colleagues) {
if (c != colleague) {
c.receive(message);
}
}
}
}
class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
}
class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
}
public class Main {
public static void main(String[] args) {
Mediator mediator = new ConcreteMediator();
Colleague colleague1 = new ConcreteColleague1(mediator);
Colleague colleague2 = new ConcreteColleague2(mediator);
mediator.addColleague(colleague1);
mediator.addColleague(colleague2);
colleague1.send("Hello, world!");
colleague2.send("Hello, colleague1!");
}
}
在这个示例中,中介者类是Mediator
类,同事类是Colleague
类,具体中介者类是ConcreteMediator
类,具体同事类是ConcreteColleague1
类和ConcreteColleague2
类。
在main
方法中,我们首先创建了一个中介者对象,然后创建了两个同事对象并将其与中介者对象关联起来。接下来,我们调用同事对象colleague1
的send
方法发送一条消息,中介者对象将这条消息发送给另一个同事对象colleague2
。最后,我们调用同事对象colleague2
的send
方法发送一条消息,中介者对象将这条消息发送给同事对象colleague1
。
通过这个示例,我们可以看到中介者模式是如何将对象之间的交互封装在中介对象中的,从而降低了对象之间的耦合度,提高了系统的灵活性。