中介者模式,又称为调停者模式或调解者模式
1.中介者模式结构图
-
示例代码
// 抽象中介类 public abstract class Mediator { protected ConcreteColleagueA concreteColleagueA; protected ConcreteColleagueB concreteColleagueB; public void setConcreteColleagueA(ConcreteColleagueA concreteColleagueA) { this.concreteColleagueA = concreteColleagueA; } public void setConcreteColleagueB(ConcreteColleagueB concreteColleagueB) { this.concreteColleagueB = concreteColleagueB; } public abstract void methodA(); public abstract void methodB(); } // 具体中介类 public class ConcreteMediator extends Mediator{ public void methodA(){ concreteColleagueB.doWorkB(); } public void methodB(){ concreteColleagueA.doWorkA(); } } // 抽象同事类 public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } } // 具体同事类A public class ConcreteColleagueA extends Colleague{ public ConcreteColleagueA(Mediator mediator) { super(mediator); } public void selfMethodA(){ mediator.methodA(); } public void doWorkA(){ System.out.println("具体处理对象A开始处理问题"); } } // 具体同事类B public class ConcreteColleagueB extends Colleague{ public ConcreteColleagueB(Mediator mediator) { super(mediator); } public void selfMethodB(){ mediator.methodB(); } public void doWorkB(){ System.out.println("具体处理对象B开始处理问题"); } } // 测试类 public class MediatorTest { public static void main(String[] args) { ConcreteMediator mediator = new ConcreteMediator(); ConcreteColleagueA colleagueA = new ConcreteColleagueA(mediator); ConcreteColleagueB colleagueB = new ConcreteColleagueB(mediator); mediator.setConcreteColleagueA(colleagueA); mediator.setConcreteColleagueB(colleagueB); colleagueA.selfMethodA(); } }
-
总结:
优点:由多对多关系转化为一对多,降低了类间的耦合,符合迪米特法则;
缺点:当同事类复杂较多时,中介者就会变得臃肿且不易维护.
-