设计模式—适配器模式
介绍
代码
接口
定义媒体播放器接口 MediaPlayer
,其中 play
方法用于播放媒体文件
public interface MediaPlayer {
public void play(String audioType, String fileName);
}
定义高级播放器接口 AdvancedMediaPlayer
,规定指定类型媒体的播放方法
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
适配器类
引入适配器类 MediaAdapter
,实现 MediaPlayer
接口, 包含成员 AdvancedMediaPlayer
。这样在调用 MediaPlayer
的 play
方法的时候,可以转接到 AdvancedMediaPlayer
的 playVlc
方法和 playMp4
方法,这就是适配器类的作用:表面上 A 类的行为,用户不知道调用的实际是 B 类,也就是适配器类完成了两个类行为的对接
public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String autioType) {
if(autioType.equalsIgnoreCase("vlc")) {
advancedMediaPlayer = new VlcPlayer();
} else if(autioType.equalsIgnoreCase("mp4")) {
advancedMediaPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")) {
advancedMediaPlayer.playVlc(fileName);
} else if(audioType.equalsIgnoreCase("mp4")) {
advancedMediaPlayer.playMp4(fileName);
}
}
}
实体类
实体类 AudioPlayer
实现 MediaPlayer
接口
public class AudioPlayer implements MediaPlayer {
MediaPlayer mediaPlayer;
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("mp3")){
System.out.println("Playing mp3 file. Name: " + fileName);
} else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
mediaPlayer = new MediaAdapter(audioType);
mediaPlayer.play(audioType, fileName);
}else{
System.out.println("Invalid media.");
}
}
}
AdvancedMediaPlayer
接口的两个实现类 Mp4Player
、VlcPlayer
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
// do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: " + fileName);
}
}
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file. Name: " + fileName);
}
@Override
public void playMp4(String fileName) {
// do nothing
}
}
测试
public class AdapterTest {
@Test
void test() {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
audioPlayer.play("avi", "mind me.avi");
}
}