同事抽象类
public abstract class Colleague {private Mediator mediator;public abstract void play(String data);
}
视频同事
public class AudioColleague extends Colleague {public void play(String data) {System.out.println("画外音是:" + data);}
}
光驱同事
public class CdColleague extends Colleague {private String data = "";public void play(String data) {this.data = data;System.out.println("从cd中读取数据:" + data);getMediator().change(this);}
}
处理器同事
public class CpuColleague extends Colleague {private String videoData = "";//读取出来的视频数据private String audioData = "";//读取出来的音频数据public void play(String data) {//处理数据String[] split = data.split(",");this.videoData = split[0];this.audioData = split[1];System.out.println("从cpu中读取视频:" + videoData);System.out.println("从cpu中读取音频:" + audioData);getMediator().change(this);}
}
声音同事
public class VideColleague extends Colleague {public void play(String data) {System.out.println("您正在观看的是:" + data);}
}
中介者接口
public interface Mediator { void change(Colleague c); }
主板中介者类
public class MainBoardMediator implements Mediator {private Colleague cd;private Colleague cpu;private Colleague video;private Colleague audio;@Overridepublic void change(Colleague c) {if (c instanceof CdColleague) {afterCdReadData((CdColleague) c);} else if (c instanceof CpuColleague) {afterCpuReadData((CpuColleague) c);}}private void afterCdReadData(CdColleague cd) {//光驱读取数据后与其他对象交互String data = cd.getData();cpu.play(data);}private void afterCpuReadData(CpuColleague cd) {//cpu读取数据后与其他对象交互String videoData = cd.getVideoData();String audioData = cd.getAudioData();video.play(videoData);audio.play(audioData);}
}
演示类
public class Demo {public static void main(String[] args) {MainBoardMediator mediator = new MainBoardMediator();Colleague audio = new AudioColleague(mediator);Colleague cd = new CdColleague(mediator);Colleague cpu = new CpuColleague(mediator);Colleague video = new VideColleague(mediator);mediator.setAudio(audio);mediator.setCd(cd);mediator.setCpu(cpu);mediator.setVideo(video);cd.play("CCTV,天气预报");}
}
演示结果
为了使代码博客代码更简洁,我省略了构造方法和set/get方法