中介者模式(Mediator Pattern),又称调停者模式,是行为类模式的一种。
定义
用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变他们的交互。
类图及组成

- 抽象中介者:定义好同事类对象到中介者对象的接口,用于各个同事类之间的通信。一般包括一个或几个抽象的事件方法,并由子类去实现。
- 中介者实现类:从抽象中介者继承而来,实现抽象中介者中定义的事件方法。从一个同事类接收消息,然后通过消息影响其他同时类。
- 同事类:
- 同事类实现类:如果一个对象会影响其他的对象,同时也会被其他对象影响,那么这两个对象称为同事类。同事类一般由多个组成,他们之间相互影响,相互依赖。在中介者模式中,同事类之间必须通过中介者才能进行消息传递。
优点
- 简化了对象之间的关系,将系统的各个对象之间的关系进行封装,将各个同事类进行解耦,使系统成为松耦合系统。
- 减少子类的生成。
- 减少各同事类的设计与实现。
缺点
由于中介者对象(中介者模式的核心)封装了各对象间的相互关系,导致其变得非常复杂,系统维护困难。
原理
中介者模式通过中介者类简化了系统的结构,将系统中有关对象引用的其他对象数目减到最少,将网状结构变为星型结构,中介者对象在这里起到中转和协调作用。

中介者模式和外观模式的区别?
- 中介者介于子系统和子系统之间,外观模式介于客户和子系统之间。
- 外观模式将原有复杂逻辑提取到一个统一的接口,简化客户端的使用。中介者模式并没有改变客户原有的习惯,是隐藏在逻辑后面的,使得代码逻辑清晰可用。
注:当系统中连续出现‘多对多’交互复杂的对象群,不要急于使用中介者模式,首先反思系统的设计是否合理。即使使用中介者模式时也要注意控制中介者类的大小。
案例代码
//抽象中介者类
public abstract class Mediator {
public abstract void send(String message, Colleague colleague);
}
//中介者实现类
public class ConcreteMediator extends Mediator {
// 需要了解所有的具体同事对象
private ConcreteColleague1 c1;
private ConcreteColleague2 c2;
public ConcreteColleague1 getC1() {
return c1;
}
public void setC1(ConcreteColleague1 c1) {
this.c1 = c1;
}
public ConcreteColleague2 getC2() {
return c2;
}
public void setC2(ConcreteColleague2 c2) {
this.c2 = c2;
}
@Override
public void send(String message, Colleague colleague) {
// 重写发送信息的方法,根据对象做出选择判断,通知对象
if (colleague == c1) {
c2.notifyMsg(message);
} else {
c1.notifyMsg(message);
}
}
}
//抽象同事类
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void sendMsg(String message);
public abstract void notifyMsg(String message);
}
//同事类实现类
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
@Override
public void sendMsg(String message) {
mediator.send(message, this);
}
@Override
public void notifyMsg(String message) {
System.out.println("同事1得到消息:" message);
}
}
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
@Override
public void sendMsg(String message) {
mediator.send(message, this);
}
@Override
public void notifyMsg(String message) {
System.out.println("同事2得到消息:" message);
}
}
-------------------------------------------------------------------------------------
来源:http://www./content-4-215351.html
|