设计模式——行为型之中介者模式
将服务提供方的接口重新封装成一个新类,服务调用方通过新类的方法间接调用原始接口,这样的行为叫中介者模式
中介者模式适合多个不同类型的一类实例互相调用的情况,将调用和执行解耦,实际上是调用者将请求委托给中介者调用
中介者模式由3部分组成:
- 调用者/接收者的抽象类,抽象出不同接收者的相同点
- 调用者/接收者,实现具体的执行逻辑
- 中介者,代替调用者调用接收者
抽象类:
public abstract class IObject {
protected Mediator mediator;
public IObject(Mediator mediator) {
this.mediator = mediator;
}
protected abstract void receive(String paramA);
public abstract void tellSb(IObject iObject,String paramA);
}
调用者/接收者(B、C省略):
public class ObjectA extends IObject{
public ObjectA(Mediator mediator) {
super(mediator);
}
//作为调用者时执行
@Override
public void tellSb(IObject iObject, String paramA) {
mediator.handleEvent(iObject,paramA);
}
//作为接收者时之行
@Override
public void receive(String paramA) {
System.out.println("A receive "+paramA);
}
}
中介者:
public class Mediator {
public void handleEvent(IObject iObject,String param){
iObject.receive(param);
}
}
使用:
public static void main(String[] args) {
final Mediator mediator = new Mediator();
final IObject objectA = new ObjectA(mediator);
final IObject objectB = new ObjectB(mediator);
final IObject objectC = new ObjectC(mediator);
objectA.tellSb(objectB,"abc");
objectA.tellSb(objectC,"def");
objectB.tellSb(objectA,"hij");
objectC.tellSb(objectA,"klm");
}
B receive abc
C receive def
A receive hij
A receive klm