0%

设计模式-中介者模式

中介者模式(Mediator pattern),属于行为型模式,去除多个对象之间复杂调用关系,增加中介者,强制所有对象通过中介者交互。

结构


涉及到了四个角色,Mediator(中介者)、ConcreteMediator(具体中介者)、Colleague(同事)、ConcreteColleague(具体同事)

同事

Colleague,包含对中介者的引用,示例如下

1
2
3
4
5
6
7
8
public abstract class Department {
protected Mediator mediator;

public Department(Mediator mediator)
{
this.mediator = mediator;
}
}

中介者

Mediator,接口或抽象类,包含与同事通讯的方法,示例如下

1
2
3
public interface Mediator {
void notify(String message,Department department);
}

具体同事

ConcreteColleague,具体同事之间互不感知,必须和中介进行通讯,示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Finance extends Department{
public Finance(Mediator mediator){
super(mediator);
}
void grant(){
System.out.println("财政部拨款");
mediator.notify("需要重建房屋",this);
}
//获得消息
void GetMessage(String message)
{
System.out.println("财政部获得消息:" + message);
}
}

具体中介者

ConcreteMediator,封装不同组件之间的关系,保存所有同事的引用,示例如下

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
public class Government implements Mediator {
private Construction construction;
private Defense defense;
private Finance finance;

void setConstruction(Construction construction){
this.construction = construction;
}

void setDefense(Defense defense){
this.defense = defense;
}

void setFinance(Finance finance){
this.finance = finance;
}

void dealDisaster() {
System.out.println("处理灾害");
finance.grant();
}

void defend() {
System.out.println("处理入侵");
defense.fight();
}

void develop() {
System.out.println("发展");
construction.buildPalace();
}

@Override
public void notify(String message, Department department) {
if(department == construction)
{
finance.GetMessage(message);
}
if(department == defense)
{
finance.GetMessage(message);
}
if(department == finance)
{
construction.GetMessage(message);
}
}
}

客户端

对如上代码测试,示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Client {
public static void main(String[] args) {
Government government = new Government();

Construction construction = new Construction(government);
Defense defense = new Defense(government);
Finance finance = new Finance(government);

government.setConstruction(construction);
government.setDefense(defense);
government.setFinance(finance);

// defense.fight();
// construction.buildPalace();
// finance.grant();

// government.develop();
// government.defend();
government.dealDisaster();
}
}

output:

1
2
3
处理灾害
财政部拨款
建造部获得消息:需要重建房屋

优缺点

  • 降低了具体同事类之间的耦合,所有具体类只依赖于中介者
  • 中介类可能变得很大

完整代码

完整代码已上传,项目地址https://github.com/yuan0824/DesignPattern

参考资料