中介者模式

根据面向对象的七大设计原则中的迪米特原则,也就是最少知道原则实现低耦合高内聚的设计思想,将对象之间的交互隔离开来,但不缺乏功能的完整性,这就是中介者模式的核心思想,简单来说就是其他所有需要交互的对象都与中介者对象相关联,通过中介者的操作实现对象间的交互

Meditor.java
java public abstract class Mediator { public abstract void send(String msg, WeChat weChat); }

SpecificMeditor.java
```java
public class SpecificMediator extends Mediator {

private A a;
private B b;

public A getA() {
    return a;
}

public void setA(A a) {
    this.a = a;
}

public B getB() {
    return b;
}

public void setB(B b) {
    this.b = b;
}

@Override
public void send(String msg, WeChat weChat) {
    if (weChat == a){
        b.notify(msg);
    }
    else {
        a.notify(msg);
    }
}

}public abstract class WeChat {

private Mediator mediator;

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

}
```

WeChat.java
```java
public abstract class WeChat {

private Mediator mediator;

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

}
```

A.java
```java
public class A extends WeChat {

private Mediator mediator;

public A(Mediator mediator) {
    super(mediator);
    this.mediator = mediator;
}

public void send(String msg){
    mediator.send(msg, this);
}

public void notify(String msg){
    System.out.println("B-->A A收到msg:"+msg);
}

}
```

B.java
```java
public class B extends WeChat {

private Mediator mediator;

public B(Mediator mediator) {
    super(mediator);
    this.mediator = mediator;
}

public void send(String msg){
    mediator.send(msg, this);
}

public void notify(String msg){
    System.out.println("A-->B B收到msg:"+msg);
}

}
```

TestMeditor.java
java public class TestMediator { public static void main(String[] args) { SpecificMediator mediator = new SpecificMediator(); A a = new A(mediator); B b = new B(mediator); mediator.setA(a); mediator.setB(b); a.send("天王盖地虎"); b.send("小鸡炖蘑菇"); } }

Run result

A-->B B收到msg:天王盖地虎
B-->A A收到msg:小鸡炖蘑菇

从这个例子可以看出消息实际上都是通过mediator来实现交互的,只不过需要再创建交互对象的时候需要“认识”mediator即可,这种行为型模式也有缺点,中介者需要认识所有对象,使得其组织变得难以维护,而且不能在职责混乱的时候使用

02-10 17:21