做网站后台要学什么人教版优化设计电子书
中介者模式
- 描述
- 基本使用
- 使用
描述
为了简化多个类间复杂的耦合关系,单独定义一个中介者
将边界交互的部分交给中介者,从而简化各个类内部逻辑
个人建议在3个及以上的类间存在复杂交互关系时再考虑中介者,否则可能反而增加系统复杂度
基本使用
- 定义抽象业务对象(引用中介者)
public abstract class AbstractColleague {protected AbstractMediator mediator;public AbstractColleague(AbstractMediator _mediator) {this.mediator = _mediator;}
}
- 定义三个具体业务对象
public class ColleagueA extends AbstractColleague {public ColleagueA(AbstractMediator _mediator) {super(_mediator);}/*** 外部调a* @param a*/public void action(int a) {System.out.println("a..." + a);}public void action2() {System.out.println("a 内部业务");this.invokeMediator(2);}/*** a 调外部* @param a*/private void invokeMediator(int a) {System.out.println("a外部交互..." + a);mediator.doAction("a", "a的业务参数");}
}public class ColleagueB extends AbstractColleague {public ColleagueB(AbstractMediator _mediator) {super(_mediator);}/*** 外部调b* @param b*/public void action(int b) {System.out.println("b..." + b);}public void action2() {System.out.println("b 内部业务");this.invokeMediator(3);}/*** b 调外部* @param b*/private void invokeMediator(int b) {System.out.println("invokeMediator..." + b);mediator.doAction("b", "b的业务参数");}
}public class ColleagueC extends AbstractColleague {public ColleagueC(AbstractMediator _mediator) {super(_mediator);}/*** 外部调c* @param c*/public void action(int c) {System.out.println("c..." + c);}public void action2() {System.out.println("c 内部业务");this.invokeMediator(3);}/*** c 调外部* @param c*/private void invokeMediator(int c) {System.out.println("invokeMediator..." + c);mediator.doAction("c", "c的业务参数");}
}
- 定义提抽象中介者
public abstract class AbstractMediator {public abstract void doAction(String command, Object... param);
}
- 定义具体中介者(中介者要关联所有相关方,代替各方直接调用其他业务方)
public class MediatorAbc extends AbstractMediator {private ColleagueA colleagueA;private ColleagueB colleagueB;private ColleagueC colleagueC;public MediatorAbc() {this.colleagueA = new ColleagueA(this);this.colleagueB = new ColleagueB(this);this.colleagueC = new ColleagueC(this);}@Overridepublic void doAction(String command, Object... param) {switch (command) {case "a":// a -> 调用 b cthis.colleagueB.action(param.length);this.colleagueC.action(param.length);break;case "b":// b -> 调用 a cthis.colleagueA.action(param.length);this.colleagueC.action(param.length);break;case "c":// c -> 调用 a bthis.colleagueA.action(param.length);this.colleagueB.action(param.length);break;default:throw new RuntimeException();}}
}
使用
其实就是字面意思,将和其他模块交互的部分交给中介完成(由中介去沟通各方 这和现实中的中介如出一辙)
public class Sample {public static void main(String[] args) {ColleagueA colleagueA = new ColleagueA(new MediatorAbc());colleagueA.action2();}
}