Fork me on GitHub

中介者模式

中介者模式主要是解决两个对象间相互作用时产生的耦合

这里举一个简单的电脑组装的例子,电脑中的组件,如CPU、显卡、内存等等都是通过主板进行工作,主板就扮演着一个中介者的角色

抽象中介者类

1
2
3
public abstract class Mediator {
public abstract void changed(Colleague colleague);
}

抽象组件类

1
2
3
4
5
6
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
}

具体组件类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class CDDevice extends Colleague {

private String data;

public CDDevice(Mediator mediator) {
super(mediator);
}

public String read() {
return data;
}

public void load() {
data = "VideoData,SoundData";
mediator.changed(this);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class CPU extends Colleague {
private String dataVideo,dataSound;
public CPU(Mediator mediator) {
super(mediator);
}

public String getDataSound() {
return dataSound;
}

public String getDataVideo() {
return dataVideo;
}

public void decodeData(String data) {
String[] tmp = data.split(",");
dataVideo = tmp[0];
dataSound = tmp[1];
mediator.changed(this);
}
}
1
2
3
4
5
6
7
8
9
public class GraphicsCard extends Colleague {
public GraphicsCard(Mediator mediator) {
super(mediator);
}

public void videoPlay(String data) {
System.out.println("Video: "+ data);
}
}
1
2
3
4
5
6
7
8
9
public class SoundCard extends Colleague {
public SoundCard(Mediator mediator) {
super(mediator);
}

public void soundPlay(String data){
System.out.println("Sound: "+data);
}
}

具体中介者

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
public class MainBoard extends Mediator {
private CDDevice cdDevice;
private CPU cpu;
private SoundCard soundCard;
private GraphicsCard graphicsCard;
@Override
public void changed(Colleague colleague) {
if (colleague == cdDevice) {
handleCD((CDDevice) colleague);
} else if (colleague == cpu) {
handleCPU((CPU)colleague);
}
}

private void handleCD(CDDevice cdDevice) {
cpu.decodeData(cdDevice.read());
}

private void handleCPU(CPU cpu) {
soundCard.soundPlay(cpu.getDataSound());
graphicsCard.videoPlay(cpu.getDataVideo());
}

public void setCdDevice(CDDevice cdDevice) {
this.cdDevice = cdDevice;
}

public void setCpu(CPU cpu) {
this.cpu = cpu;
}

public void setSoundCard(SoundCard soundCard) {
this.soundCard = soundCard;
}

public void setGraphicsCard(GraphicsCard graphicsCard) {
this.graphicsCard = graphicsCard;
}
}

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
MainBoard mainBoard = new MainBoard();
CDDevice cdDevice = new CDDevice(mainBoard);
CPU cpu = new CPU(mainBoard);
GraphicsCard graphicsCard = new GraphicsCard(mainBoard);
SoundCard soundCard = new SoundCard(mainBoard);
mainBoard.setCdDevice(cdDevice);
mainBoard.setCpu(cpu);
mainBoard.setGraphicsCard(graphicsCard);
mainBoard.setSoundCard(soundCard);
cdDevice.load();
}
}

中介者类负责各个组件之间的配合,所以各个组件之间的耦合度会降低,最后只需要启动一个组件的动作,通信工作就由中介者负责