定义
用一个中介对象来封装一系列对象之间的交互,中介者使得各个对象不需要显示的相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互.
即当程序系统中出现多对多的对象之间的相互联系时,可以考虑使用中介者模式,因为可能是系统设计的不合理造成了这种多对多的关系。
结构图
代码
//中介者接口
public Interface Mediator
{
public void send(String message,Colleague colleague);
//定义一个发送消息的方法,得到同事对象和发送消息
}
//抽象同事类
public class Colleague
{
protected Mediator mediator;
//设置中介者对象
public Colleague(Mediator mediator)
{
this.mediator=mediator;
}
}
/具体同事类
public class ConcreteColleague1 extends Colleague
{
public ConcreteColleague1(Mediator mediator)
{
super(mediator);
}
public void send(String message)
{
mediator.send(message,this);
}
public void notify(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 notify(String message)
{
System.out.println("同事2得到消息:"+message);
}
}
//具体中介者类
public class ConcreteMediator implements Mediator
{
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public void setColleague1(ConcreteColleague1 colleague)
{
this.colleague1=colleague;
}
public void setColleague2(ConcreteColleague2 colleague)
{
this.colleague2=colleague;
}
public void send(String message,Colleague colleague)
{
if(colleague instanceof ConcreteColleague1)
{
coleague2.notify(message);
}
else
{
coleague1.notify(message);
}
}
}
//客户端调用
public static void main(Strng[] args)
{
ConcreteMediator mediator=new ConcreteMediator();
ConcreteColleague1 c1=new ConcreteColleague1(mediator);
ConcreteColleague2 c2=new ConcreteColleague2(mediator);
mediator.setColleague1(c1);
mediator.setColleague2(c2);
c1.send("代码写完了吗?");
c2.send("还没。。。");
}
缺点
虽然使用中介者模式减少了Colleague具体对象之间的耦合度,但也同时使得具体中介者承担了过多的责任,那么当系统中的这种多对多的相联系的对象过多时,中介者就会变得很复杂,如果它出了问题,那么整个系统也就出问题了。