一、介绍
中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
Colleague叫作抽象同事类,而ConcreteColleague是具体同事类,每个具体同事只知道自己的行为,而不了解其他同事类的情况,但他们却都认识中介者对象,Mediator是抽象中介者,定义了同事对象到中介者对象的接口,ConcreteMediator是具体中介者对象,实现抽象类的方法,它需要知道所有具体同事类,并从具体同事接收消息,向具体同事对象发出命令。
二、代码实现
//抽象同事类 public abstract 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){ this.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){ this.mediator.send(message,this); } public void notify(String message){ System.out.println("同事2得到消息:"+message); } } //中介类 public abstract class Mediator { //抽象消息发送类 public abstract void send(String message, Colleague colleague); } public class ConcreteMediator extends Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public void setColleague1(ConcreteColleague1 colleague1) { this.colleague1 = colleague1; } public void setColleague2(ConcreteColleague2 colleague2) { this.colleague2 = colleague2; } @Override public void send(String message, Colleague colleague) { if (colleague == colleague1) { colleague2.notify(message); } else { colleague1.notify(message); } } }
测试
public class Client { public static void main(String[] args) { ConcreteMediator m=new ConcreteMediator(); ConcreteColleague1 c1=new ConcreteColleague1(m); ConcreteColleague2 c2=new ConcreteColleague2(m); m.setColleague2(c2); m.setColleague1(c1); c1.send("hello"); c2.send("hello two"); } }