中介者模式
定义
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。
一般用于一组对象定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,又不想生成太多子类的场合。
优点:
- Mediator减少了各个Colleagues之间的耦合,使得可以独立的改变和复用各个Colleague类和Mediator。
- 由于把对象如何协作做了抽象,将中介作为一个独立的概念封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到它们之间的交互上来,从一个更宏观的角度看待系统。
缺点
- 容易误用,当出现”多对多“交互复杂的对象群时,要先考虑系统在设计上是否合理,再用中介者模式。
- 由于ConcreteMediator实现了集中化,于是交互复杂化变为了中介者的复杂性。
UML图
用例
联合国安理会在各国间组织发言
联合国机构类:Mediator
abstract class UnitedNations{
//声明
public abstract void declare(string message, Country colleague);
}
国家类:College
abstract class Country{
protected UnitedNations mediator;
public Country(UnitedNations mediator){
this.mediator = mediator;
}
}
美国类:ConcreteColleague1
class USA extends Country{
public USA(UnitedNations mediator){
super(mediator);
}
//声明
public void declare(string message){
mediator.declare(message, this);
}
//获取消息
public void getMessage(string message){
System.out.println("美国获得对方消息:" + message);
}
}
伊拉克:ConcreteColleague2
class Iraq extends Country{
public Iraq(UnitedNations mediator){
super(mediator);
}
//声明
public void declare(string message){
mediator.declare(message, this);
}
//获取消息
public void getMessage(string message){
System.out.println("伊拉克获得对方消息:" + message);
}
}
联合国安全理事会:ConcreteMediator
class UnitedNationsSecurity extends UnitedNations{
private USA colleague1;
private Iraq colleague2;
//美国
public USA Colleague1 { set { colleague1 = value; } }
//伊拉克
public Iraq Colleague2 { set { colleague2 = value; } }
@override
public void declare(string message, Country colleague){
if (colleague == colleague1)
colleague2.getMessage(message);
else
colleague1.getMessage(message);
}
}
客户端
static void Main(string[] args){
UnitedNationsSecurity UNSC = new UnitedNationsSecurity();
USA c1 = new USA(UNSC);
Iraq c2 = new Iraq(UNSC);
UNSC.Colleague1 = c1;
UNSC.Colleague2 = c2;
c1.declare("不准研发核武器,否则开战");
c2.declare("没研发,开战就开战");
}