作用:当复杂功能应用之间重复调用时,在中间添加一层中介者包装服务,对外提供简单、通用和易扩展的服务能力。比如“联合国” 就是中介者,各个国家可以通过“联合国”通信。
接下来看代码:
模拟人之间沟通,通过中介。
1. 抽象中介者类
public abstract class Mediator { abstract void send(String message , Colleague colleague); }
2. 抽象同事类
public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator){ this.mediator = mediator; } abstract void send(String message); }
3. 具体中介者类
public class ConcreteMediator extends Mediator{ private ConcreteColleague1 concreteColleague1; private ConcreteColleague2 concreteColleague2; public ConcreteMediator setConcreteColleague1(ConcreteColleague1 concreteColleague1) { this.concreteColleague1 = concreteColleague1; return this; } public ConcreteMediator setConcreteColleague2(ConcreteColleague2 concreteColleague2) { this.concreteColleague2 = concreteColleague2; return this; } @Override public void send(String message, Colleague colleague) { if(colleague == concreteColleague1) { concreteColleague2.notify(message); }else { concreteColleague1.notify(message); } } }
4. 同事实现类
public class ConcreteColleague1 extends Colleague{ public ConcreteColleague1(Mediator mediator) { super(mediator); } @Override public void send(String message) { mediator.send(message,this); } public void notify(String message){ System.out.println("NO1 message: " + message); } } public class ConcreteColleague2 extends Colleague{ public ConcreteColleague2(Mediator mediator) { super(mediator); } @Override public void send(String message) { mediator.send(message,this); } public void notify(String message){ System.out.println("NO2 message:" + message); } }
5. 测试类
public class Test { public static void main(String[] args) { ConcreteMediator concreteMediator = new ConcreteMediator(); ConcreteColleague1 concreteColleague1 = new ConcreteColleague1(concreteMediator); ConcreteColleague2 concreteColleague2 = new ConcreteColleague2(concreteMediator); concreteMediator.setConcreteColleague1(concreteColleague1); concreteMediator.setConcreteColleague2(concreteColleague2); concreteColleague1.send("你好!!!!"); concreteColleague2.send("好的。。。"); } } /**** > Task :Test.main() NO2 message:你好!!!! NO1 message: 好的。。。 ***/
减少了同事之间的耦合度。。。