中介者模式
用一个中介对象封装一系列的对象交互,中介者使得各个对象不需要显式的相互作用,从而使其解耦合,还可以独立的改变它们之间的交互,这些对象不希望自己处理各种关系,交给中介者来处理
直接引用
核心概念
- Mediator 中介者接口,定义各个同事之间交互需要的方法
- ConcreteMediator 具体的中介者实现
- Colleague 同事类的定义
- ConcreteColleague 同事类的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
public interface Mediator { void changed(Colleague colleague); }
public abstract class Colleague { private Mediator mediator;
public Colleague(Mediator mediator){ this.mediator = mediator; }
public Mediator getMediator() { return mediator; } }
public class ConcreteColleagueA extends Colleague{ public ConcreteColleagueA(Mediator mediator) { super(mediator); }
public void businsess(){ getMediator().changed(this); } }
public class ConcreteColleagueB extends Colleague{ public ConcreteColleagueB(Mediator mediator) { super(mediator); }
public void businsess(){ getMediator().changed(this); } }
public class ConcreteMediator implements Mediator { private ConcreteColleagueA concreteColleagueA;
private ConcreteColleagueB concreteColleagueB;
public void setConcreteColleagueA(ConcreteColleagueA concreteColleagueA) { this.concreteColleagueA = concreteColleagueA; }
public void setConcreteColleagueB(ConcreteColleagueB concreteColleagueB) { this.concreteColleagueB = concreteColleagueB; }
@Override public void changed(Colleague colleague) { if(colleague == concreteColleagueA){ System.out.println("concreteColleagueA 完成工作了"); } else if(colleague == concreteColleagueB){ System.out.println("concreteColleagueB 完成工作了"); } } }
|
优缺点
优点
- 松散耦合,使得多个对象之间不互相依赖,而将交互都封装到中介者对象中
- 集中控制交互
- 多对多变成一对多
缺点
- 过度集中化,如果同事之间交互特别多的话,会非常的复杂
使用场景
- 一组对象之间的通信方式比较复杂,导致相互依赖、结构混乱,可以用中介者模式将这些对象相互的交互管理起来
- 一个对象引用很多对象,并直接和这些对象交互,导致难以复用,可以用中介者模式将交互封装起来