package com.design; /**中介者模式 * 优点: 简化了对象之间的交互:它用中介者和同事的一对多交互代替了原来同事之间的多对多交互,一对多关系更容易理解、维护和扩展, 将原本难以理解的网状结构转换成相对简单的星型结构。 各同事对象之间解耦:中介者有利于各同事之间的松耦合,我们可以独立的改变和复用每一个同事和中介者,增加新的中介者和新的 同事类都比较方便,更好地符合“开闭原则”。 减少子类生成:中介者将原本分布于多个对象间的行为集中在一起,改变这些行为只需生成新的中介者子类即可,这使各个同事类可 被重用,无须对同事类进行扩展。 缺点: 中介者会庞大,变得复杂难以维护。 * Created by nicknailo on 2018/8/29. */ public class MediatorPattern { public static void main(String[] args) { UnitedNationsSecurityCouncil UNSC = new UnitedNationsSecurityCouncil(); USA c1 = new USA(UNSC); Iraq c2 = new Iraq(UNSC); UNSC.setColleague1(c1); UNSC.setColleague2(c2); c1.declare("不准研发核武器,否则发动战争"); c2.declare("我们没有核武器,也不怕侵略。"); } } abstract class UnitedNations{ public abstract void declare(String message,Country colleague); } abstract class Country{ protected UnitedNations mediator; public Country(UnitedNations mediator) { this.mediator = mediator; } } class USA extends Country{ public USA(UnitedNations mediator) { super(mediator); } // 声明 public void declare(String message){ mediator.declare(message,this); } // 获得消息 public void GetMessage(String message){ System.out.println( "美国获得对方信息: " + message ); } } class Iraq extends Country{ public Iraq(UnitedNations mediator) { super(mediator); } public void declare(String message) { mediator.declare(message, this); } public void GetMessage(String message){ System.out.println( "伊拉克获得对方信息: " + message ); } } class UnitedNationsSecurityCouncil extends UnitedNations{ private USA colleague1; private Iraq colleague2; public USA getColleague1() { return colleague1; } public void setColleague1(USA colleague1) { this.colleague1 = colleague1; } public Iraq getColleague2() { return colleague2; } public void setColleague2(Iraq colleague2) { this.colleague2 = colleague2; } @Override public void declare(String message, Country colleague) { if (colleague == colleague1){ colleague2.GetMessage(message); }else{ colleague1.GetMessage(message); } } }