设计模式之中介者模式
# 设计模式之中介者模式
# 一、简介
用一个中介对象来封装一系列的对象交互,来避免对象之间的直接交互
# 二、实现方式
Mediator(抽象中介者):用来定义参与者与中介者之间的交互方式
// 抽象中介者 public interface Mediator { // 定义处理逻辑 void doEvent(Colleague colleague); }
1
2
3
4
5ConcreteMediator(具体中介者):实现了
Mediator
。持有参与者对象的集合,管理和通知其它参与者// 具体中介者 @Component public class DispatchCenter implements Mediator { // 管理有哪些参与者 @Autowired private List<Colleague> colleagues; @Override public void doEvent(Colleague colleague) { for(Colleague colleague1 :colleagues){ if(colleague1==colleague){ // 如果是本身高铁信息,可以处理其他的业务逻辑 // doSomeThing(); continue; } // 通知其他参与 colleague1.message(); } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20Colleague(抽象参与者)
// 抽象参与者, 也可以使用abstract 写法 public interface Colleague { // 沟通消息 void message(); }
1
2
3
4
5ConcreteColleague(具体参与者)
// 具体参与者 @Component public class MotorCarOneColleague implements Colleague { @Override public void message() { // 模拟处理业务逻辑 System.out.println("高铁一号收到消息!!!"); } } @Component public class MotorCarTwoColleague implements Colleague { @Override public void message() { System.out.println("高铁二号收到消息!!!"); } } @Component public class MotorCarThreeColleague implements Colleague { @Override public void message() { System.out.println("高铁三号收到消息!!!"); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24测试demo
// 测试demo
public static void main(String[] args) {
// 初始化spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 获取中介者,调度中心
DispatchCenter dispatchCenter = (DispatchCenter) applicationContext.getBean("dispatchCenter");
// 一号高铁 发送消息出去
MotorCarOneColleague motorCarOneColleague = (MotorCarOneColleague) applicationContext.getBean("motorCarOneColleague");
// 通过调度中心沟通信息
dispatchCenter.doEvent(motorCarOneColleague);
// result:高铁三号收到消息!!!
// 高铁二号收到消息!!!
// 二号高铁 发送消息出去
MotorCarTwoColleague motorCarTwoColleague = (MotorCarTwoColleague)applicationContext.getBean("motorCarTwoColleague");
dispatchCenter.doEvent(motorCarTwoColleague);
// result:高铁一号收到消息!!!
// 高铁三号收到消息!!!
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23