设计模式学习笔记十八:中介者模式
设计模式学习笔记十八:中介者模式
介绍
中介者(MEDIATOR)模式属于对象行为型模式。主要目的是将对象间复杂的调用关系进行解耦。使所有的对象都通过这个中介者进行交互。
优点
- 对象解耦,提供了复用性;
- 简化了单个对象的交互逻辑;
缺点
- 中介者业务性太强,黑箱子的雏形。
其他
- 如果同事过多,逻辑过多,不管是否使用这种模式,循环调用这种事情都很难查找了。
使用场景
代码抽象良好,但是对象之间存在互相调用的情况建议使用中介者模式。
UML结构图:
代码实现
1.定义中介者,即Mediator
public interface Mediator {
public void change(Colleague colleague);
}
2.中介者具体实现。即ConcreteMediator
public class ConcreteMediator implements Mediator {
@Override
public void change(Colleague colleague) {
if (colleague instanceof ConcreteColleague1) {
concreteColleague1Call((ConcreteColleague1) colleague);
} else if (colleague instanceof ConcreteColleague2) {
concreteColleague2Call((ConcreteColleague2) colleague);
} else {
throw new UnsupportedOperationException("unspported colleague");
}
}
private void concreteColleague1Call(ConcreteColleague1 colleague) {
colleague.call();
}
private void concreteColleague2Call(ConcreteColleague2 colleague) {
colleague.call();
}
}
3.定义同事抽象,即Colleague
public abstract class Colleague {
protected Mediator mediator;
protected Colleague(Mediator mediator) {
this.mediator = mediator;
}
}
4.具体同事具体实现,即ConcreteColleague1和ConcreteColleague2
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
public void doSmth() {
System.out.println("ConcreteColleague1做了一些事情");
mediator.change(this);
}
public void call() {
System.out.println("外部调用ConcreteColleague1");
}
}
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
public void doSmth() {
System.out.println("ConcreteColleague2做了一些事情");
mediator.change(this);
}
public void call() {
System.out.println("外部调用ConcreteColleague2");
}
}
5.测试调用,TestDrive
public class Run {
public static void main(String[] args) {
Mediator mediator = new ConcreteMediator();
ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator);
ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator);
colleague1.doSmth();
colleague2.doSmth();
}
}