适配器模式
2个接口,普通播放器,高级播放器
普通播放器 MediaPlayer
public interface MediaPlayer {
void play(String audioType, String fileName);
}
高级播放器 AdvancedMediaPlayer
public interface AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName)
}
vlc播放器实现
public class VlcPlayer implements AdvancedMediaPlayer {
public void playVlc(String fileName){
System.out.println("vlc play :" + fileName);
}
public void playMp4(String fileName){
}
}
mp4播放器实现
public class Mp4Player implements AdvancedMediaPlayer {
public void playVlc(String fileName){
}
public void playMp4(String fileName){
System.out.println("mp4 play:" + fileName);
}
}
创建适配器,实现MediaPlayer
public MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String audioType){
switch(audioType){
case "vlc":
advancedMediaPlayer = new VlcPlayer();
break;
case "mp4":
advancedMediaPlayer = new Mp4Player();
break;
}
}
public void play(String audioType, String fileName){
switch(audioType){
case "vlc":
advancedMediaPlayer.playVlc(fileName);
break;
case "mp4":
advancedMediaPlayer.playMp4(fileName);
break;
}
}
}
引用适配器,进行定义开发
public AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
public void play(String audioType, String fileName){
switch(audioType){
case "mp3":
System.out.println("mp3 play:" + fileName);
break;
case "vlc":
mediaAdapter = new MediaAdapter("vlc");
mediaAdapter.play(audioType,fileName);
break;
case "mp4":
mediaAdapter = new MediaAdapter("mp4");
mediaAdapter.play(audioType,fileName);
break;
}
}
}
main函数测试
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
}
}
标签:play,String,适配器,模式,fileName,void,audioType,public
From: https://www.cnblogs.com/PythonOrg/p/17373553.html