中介者模式

中介者模式

中介对象封装一系列对象交互,使对象不需要显示地相互作用,从而使其低耦合松散,并可独立改变它们之间的交互。但是当同事类过多时,中介者的职责将变得复杂而庞大,以至于难以维护。

使用场景

当类图中出现蜘蛛网状结构。在这种情况下一定考虑使用中介者模式

类图

代码

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
90
91
92
93
public abstract class AbstractColleague {
protected AbstractMediator mediator;

public AbstractColleague(AbstractMediator mediator) {
this.mediator = mediator;
}
}

public class DevelopColleague extends AbstractColleague {

private String task;

public DevelopColleague(AbstractMediator mediator) {
super(mediator);
}

public void acceptTask(String task) {
this.task = task;
System.out.println("开发确认任务:" + task);
}

public void doneTask() {
System.out.println("开发完成任务:" + task);
super.mediator.reportProgress(task);
}
}

public class ProjectManageColleague extends AbstractColleague {
public ProjectManageColleague(AbstractMediator mediator) {
super(mediator);
}

public void generateTask() {
String task = "用户模块";
System.out.println("PM生成任务:"+task);
super.mediator.developColleague.acceptTask(task);
}

public void taskProgress(String task) {
System.out.println("PM确认项目进度:" + task + "完成");
}
}

public abstract class AbstractMediator {
protected DevelopColleague developColleague;
protected ProjectManageColleague projectManageColleague;

public DevelopColleague getDevelopColleague() {
return developColleague;
}

public void setDevelopColleague(DevelopColleague developColleague) {
this.developColleague = developColleague;
}

public ProjectManageColleague getProjectManageColleague() {
return projectManageColleague;
}

public void setProjectManageColleague(ProjectManageColleague projectManageColleague) {
this.projectManageColleague = projectManageColleague;
}

public abstract void reportProgress(String task);
public abstract void assignWork(String task);
}

public class ConcreteMediator extends AbstractMediator {

@Override
public void reportProgress(String task) {
super.projectManageColleague.taskProgress(task);
}

@Override
public void assignWork(String task) {
super.developColleague.acceptTask(task);
}
}

public class Client {
public static void main(String[] args) {
AbstractMediator mediator = new ConcreteMediator();
DevelopColleague developColleague = new DevelopColleague(mediator);
ProjectManageColleague projectManageColleague = new ProjectManageColleague(mediator);

mediator.setDevelopColleague(developColleague);
mediator.setProjectManageColleague(projectManageColleague);

projectManageColleague.generateTask();
developColleague.doneTask();
}
}