行为型设计模式之中介者模式( 二 )


创建具体同事类
public class ConcreteColleagueA extends Colleague {public ConcreteColleagueA(Mediator mediator) {super(mediator);this.mediator.setColleageA(this);}/*** 自有方法*/public void selfMethodA() {System.out.println( this.getClass().getSimpleName()+ "收到中介协作通知 , selfMethodA自有方法执行");}/*** 依赖方法*/public void depMethodA() {System.out.println( this.getClass().getSimpleName()+ " depMethodA通知中介者进行转发协作");// 中介者进行转发协作this.mediator.transferA();}}
public class ConcreteColleagueB extends Colleague {public ConcreteColleagueB(Mediator mediator) {super(mediator);this.mediator.setColleageB(this);}/*** 自有方法*/public void selfMethodB() {System.out.println(this.getClass().getSimpleName() + "收到中介协作通知 , selfMethodB自有方法执行");}/*** 依赖方法*/public void depMethodB() {System.out.println(this.getClass().getSimpleName() + " depMethodB通知中介者进行转发协作");// 中介者进行转发协作this.mediator.transferB();}}
客户端执行
public static void main(String[] args) {// 创建抽象中介者Mediator mediator = new ConcreteMediator();// 具体同事类ConcreteColleagueA colleagueA = new ConcreteColleagueA(mediator);ConcreteColleagueB colleagueB = new ConcreteColleagueB(mediator);// 中介者进行转发协作,A转发给BcolleagueA.depMethodA();System.out.println("-------------------------");// 中介者进行转发协作,B转发给AcolleagueB.depMethodB();}
ConcreteColleagueA depMethodA通知中介者进行转发协作ConcreteColleagueB收到中介协作通知 , selfMethodB自有方法执行-------------------------ConcreteColleagueB depMethodB通知中介者进行转发协作ConcreteColleagueA收到中介协作通知 , selfMethodA自有方法执行