中间桥梁,将互相不联系的事物联系起来。
public abstract class Colleague { protected Mediator mediator; /** * 用于表示几件事物的统一性,最起码是同一个媒介 * * @param mediator */ public Colleague(Mediator mediator) { this.mediator = mediator; }}
public class CDDevice extends Colleague { private String data; /** * CD唱片,包括音频,视频 * @param mediator */ public CDDevice(Mediator mediator) { super(mediator); } public String read() { return data; } public void load() { data = "视频数据,音频数据"; mediator.changed(this); // 媒介分发数据 }}
public class CPU extends Colleague { private String video, sound; public CPU(Mediator mediator) { super(mediator); } public String getVideo() { return video; } /** * 解析数据 * * @param data */ public void decodeData(String data) { String[] tmp = data.split(""); video = tmp[0]; sound = tmp[1]; mediator.changed(this); } public String getSound() { return sound; }}
public class GraphicsCard extends Colleague { public GraphicsCard(Mediator mediator) { super(mediator); } /** * 视频数据处理 * * @param data */ public void videoPlay(String data) { System.out.print("视频:" + data); }}
public class SoundCard extends Colleague { public SoundCard(Mediator mediator) { super(mediator); } /** * 音频数据处理 * @param data */ public void soundPlay(String data){ System.out.print("音频:"+ data); }}
public abstract class Mediator { /** * 通知中介改变 * * @param c */ abstract void changed(Colleague c);}
public class MainBoard extends Mediator { private CDDevice cdDevice; private CPU cpu; private GraphicsCard graphicsCard; private SoundCard soundCard; @Override void changed(Colleague c) { if (c == cdDevice) { cdDevice = (CDDevice) c; cpu.decodeData(cdDevice.read()); } else if (c == cpu) { cpu = (CPU) c; soundCard.soundPlay(cpu.getVideo()); graphicsCard.videoPlay(cpu.getSound()); } } public MainBoard setCdDevice(CDDevice cdDevice) { this.cdDevice = cdDevice; return this; } public MainBoard setCPU(CPU cpu) { this.cpu = cpu; return this; } public MainBoard setGraphicsCard(GraphicsCard graphicsCard) { this.graphicsCard = graphicsCard; return this; } public MainBoard setSoundCard(SoundCard soundCard) { this.soundCard = soundCard; return this; }}
public static void main(String[] args) { MainBoard mediator = new MainBoard(); CDDevice cdDevice = new CDDevice(mediator); CPU cpu = new CPU(mediator); GraphicsCard graphicsCa = new GraphicsCard(mediator); SoundCard soundCard = new SoundCard(mediator); mediator.setCdDevice(cdDevice).setCPU(cpu).setGraphicsCard(graphicsCa).setSoundCard(soundCard); cdDevice.load(); // CD开始放片}