中介者模式
一、定义
中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
二、示例代码
public abstract class Mediator {
public abstract void send(String message,Colleague colleague);
}
public class ConcreteMediator extends Mediator {
private ConcreteColleague1 concreteColleague1;
private ConcreteColleague2 concreteColleague2;
public void setConcreteColleague1(ConcreteColleague1 concreteColleague1) {
this.concreteColleague1 = concreteColleague1;
}
public void setConcreteColleague2(ConcreteColleague2 concreteColleague2) {
this.concreteColleague2 = concreteColleague2;
}
@Override
public void send(String message, Colleague colleague) {
if (colleague==concreteColleague1){
concreteColleague2.inform(message);
}
else {
concreteColleague1.inform(message);
}
}
}
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
public void send(String message){
mediator.send(message,this);
}
public void inform(String message)
{
System.out.println("同事1得到消息"+message);
}
}
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
public void send(String message){
mediator.send(message,this);
}
public void inform(String message)
{
System.out.println("同事2得到消息"+message);
}
}
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
}
public class Client {
public static void main(String[] args) {
ConcreteMediator mediator=new ConcreteMediator();
ConcreteColleague1 concreteColleague1=new ConcreteColleague1(mediator);
ConcreteColleague2 concreteColleague2=new ConcreteColleague2(mediator);
mediator.setConcreteColleague1(concreteColleague1);
mediator.setConcreteColleague2(concreteColleague2);
concreteColleague1.send("hello");
concreteColleague2.send("hi");
}
}
三、优缺点
中介者模式一般应用于一组对象以定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想生成太多的子类的场合。
优点:1 中介者的出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator。
2.由于把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各种本身的行为转移到它们之间的交互上来,也就是从一个更宏观的角度去看待系统。
缺点:具体中介者类由于ConcreteColleague的越来越多,而变的非常复杂,不容易维护。