目录
1.简介
中介者模式通过建立一个中介对象来封装一系列的对象交互,使得各对象之间不需要直接进行交互,从而达到解耦的作用,而且可以独立地改变他们之间的交互。
2.特点
减少类之间的依赖,把相互之间的依赖转化为依赖中介者,降低了类之间的耦合,但是这种类越多,关系就越复杂,中介者的逻辑也就越复杂。
3.形式
抽象中介者
public abstract class AMediator {
protected Colleague1 c1;
protected Colleague2 c2;
public Colleague1 getC1() {
return c1;
}
public void setC1(Colleague1 _c1) {
this.c1 = _c1;
}
public Colleague2 getC2() {
return c2;
}
public void setC2(Colleague1 _c2) {
this.c2 = _c2;
}
public abstract void method1();
public abstract void method2();
}
具体中介者
public class Mediator extends AMediator {
@Override
public void method1() {
super.c1.selfMethod1();
super.c2.selfMethod2();
}
public void method2() {
super.c2.selfMethod2();
super.c1.selfMethod1();
}
}
抽象同事类
public abstract class AColleague {
protected AMediator mediator;
public AColleague(AMediator _mediator) {
this.mediator = _mediator;
}
}
具体同事类1
public class Colleague1 extends AColleague {
public Colleague1(AMediator _mediator) {
super(_meditor);
}
public void selfMethod1() {
System.out.println("自身业务逻辑");
}
public void depMethod1() {
super.mediator.method1();
}
}
具体同事类2
public class Colleague2 extends AColleague {
public Colleague2(AMediator _mediator) {
super(_meditor);
}
public void selfMethod2() {
System.out.println("自身业务逻辑");
}
public void depMethod2() {
super.mediator.method2();
}
}