package caosc.javaModel.Mediator;
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void send(String message);
}
package caosc.javaModel.Mediator;
public abstract class Mediator {
public abstract void sendMessage(Colleague colleague,String message);
}
package caosc.javaModel.Mediator;
public class ConcreteMediator extends Mediator {
ConcreteColleague1 cc1;
ConcreteColleague2 cc2;
public ConcreteColleague1 getCc1() {
return cc1;
}
public void setCc1(ConcreteColleague1 cc1) {
this.cc1 = cc1;
}
public ConcreteColleague2 getCc2() {
return cc2;
}
public void setCc2(ConcreteColleague2 cc2) {
this.cc2 = cc2;
}
@Override
public void sendMessage(Colleague colleague, String message) {
if(colleague==cc1){
cc1.nodifyMessage(message);
}else{
cc2.nodifyMessage(message);
}
}
}
package caosc.javaModel.Mediator;
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
public void nodifyMessage(String message){
System.out.println(message);
}
@Override
public void send(String message) {
mediator.sendMessage(this, message);
};
}
package caosc.javaModel.Mediator;
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
public void nodifyMessage(String message){
System.out.println(message);
}
@Override
public void send(String message) {
mediator.sendMessage(this, message);
};
}
package caosc.javaModel.Mediator;
public class MediatorTest {
public static void main(String[] args) {
ConcreteMediator m = new ConcreteMediator();
ConcreteColleague1 cc1 = new ConcreteColleague1(m);
ConcreteColleague2 cc2 = new ConcreteColleague2(m);
m.cc1 = cc1;
m.cc2 = cc2;
cc1.send("今年加工资了吗?");
cc2.send("没有呢!");
}
}
使用场合:
1、由于把对象如何协作进行抽象,将中介作为一个独立的概念并将其封装到一个对象中,这样关注的对象就是对象各自本身的行为转到他们中间的交互上来,站在一个宏观的角度去看待系统
2、Mediator的出现,减少了各个Colleague的耦合,可以独立的改变和复用各个Colleague,Mediator
3、缺点是由于ConcreteMediator的集中处理,于是把交换复杂性变成交互者复杂性,所以ConcreteMediator比任何一个ConcreteColleagueX都复杂;