模式介绍

中介者模式是一种行为型设计模式,它定义了一个中介对象来封装一系列对象之间的交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

使用场景

  • 当对象之间存在复杂的通信方式时
  • 当一组对象以定义良好但是复杂的方式进行通信时
  • 当想定制一个分布在多个类中的行为,而又不想生成太多的子类时

代码示例

// 中介者接口
public interface Mediator {
    void notify(Component sender, String event);
}

// 抽象组件
public abstract class Component {
    protected Mediator mediator;

    public Component(Mediator mediator) {
        this.mediator = mediator;
    }

    public abstract void send(String event);
    public abstract void receive(String event);
}

// 具体组件A
public class ConcreteComponentA extends Component {
    public ConcreteComponentA(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void send(String event) {
        mediator.notify(this, event);
    }

    @Override
    public void receive(String event) {
        System.out.println("Component A received: " + event);
    }
}

// 具体中介者
public class ConcreteMediator implements Mediator {
    private ConcreteComponentA componentA;
    private ConcreteComponentB componentB;

    public void setComponentA(ConcreteComponentA componentA) {
        this.componentA = componentA;
    }

    public void setComponentB(ConcreteComponentB componentB) {
        this.componentB = componentB;
    }

    @Override
    public void notify(Component sender, String event) {
        if (sender == componentA) {
            componentB.receive(event);
        } else {
            componentA.receive(event);
        }
    }
}

优缺点

优点

  • 降低了对象之间的耦合度
  • 简化了对象之间的交互
  • 将对象之间的通信封装在中介者中

缺点

  • 中介者可能会变得过于复杂
  • 中介者可能会成为系统的瓶颈
  • 增加了系统的复杂度