中介者模式:用一个中介对象来封装一系列的对象交互。
中介者使各对象不须要显式的相互引用,从而使其耦合松散。并且能够独立的改变它们之间的交互。
使用场合:中介者模式一般应用于一组对象以定义良好可是复杂的方式进行通信的场合。以及想定制一个分布在多个类中的行为,而不是想生成太多的子类的场合。
首先定义一个中介者接口IMediator
public interface IMediator {
public void send(String message,Colleague colleague);
}
接着定义抽象同事类Colleague
public abstract class Colleague {
protected IMediator mediator;
public Colleague(IMediator mediator){
this.mediator=mediator;
}
}
接着定义详细的同事类继承Colleague 抽象同事类
public class ConcreteColleague1 extends Colleague{
public ConcreteColleague1(IMediator 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(IMediator mediator) {
super(mediator);
}
public void send(String message){
mediator.send(message, this);
}
public void notify(String message){
System.out.println("同事2获得消息:"+message);
}
}
然后定义一个详细的中介者对象ConcreteMediator继承IMediator
public class ConcreteMediator implements IMediator{
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public void setColleague1(ConcreteColleague1 colleague1){
this.colleague1=colleague1;
}
public ConcreteColleague1 getColleague1(){
return colleague1;
}
public void setColleague2(ConcreteColleague2 colleague2){
this.colleague2=colleague2;
}
public ConcreteColleague2 getColleague2(){
return colleague2;
}
@Override
public void send(String message, Colleague colleague) {
if(colleague==colleague1){
colleague2.notify(message);
}
else{
colleague1.notify(message);
}
}
}
client代码
public static void main(String[] args) {
//中间者模式
ConcreteMediator mediator=new ConcreteMediator();
ConcreteColleague1 colleague1=new ConcreteColleague1(mediator);
ConcreteColleague2 colleague2=new ConcreteColleague2(mediator);
mediator.setColleague1(colleague1);
mediator.setColleague2(colleague2);
colleague1.send("你好,中国");
colleague2.send("你好,美国");
}