1.Introduction
适配器模式是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
2.Example
音频播放器设备只能播放mp3文件,通过使用一个更高级的音频播放器来播放vlc和mp4文件
3.Code
3.1 Source
// 需要被适配的接口
public interface AdvancedMediaPlayer {
void playMp4(String fileName);
}
public class Mp4Player implements AdvancedMediaPlayer {
@Override
public void playMp4(String fileName) {
System.out.println("Play Mp4, fileName " + fileName);
}
}
3.2 Target
// 最终需要的接口
public interface MediaPlayer {
void play(String fileName);
}
3.3 Adapter
public class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter() {
this.advancedMediaPlayer = new Mp4Player();
}
@Override
public void play(String fileName) {
advancedMediaPlayer.playMp4(fileName);
}
}
3.Test
public class AdapterPatternDemo {
public static void main(String[] args) {
MediaPlayer mediaPlayer = new MediaAdapter();
mediaPlayer.play("阿甘正传");
}
}
网友评论