适配器模式
1、简介
适配器(Adapater Pattern)作为二个不兼容接口的桥梁。
例如:内存卡 -> 读卡器 -> 电脑硬盘
简单来说,就是将一个类的接口转换为客户希望的另一个接口,使得原本因为接口不兼容的那些类可以一起工作。
关键思想: 继承或者依赖已有的对象,实现想要的目标接口
2、使用
// 高级播放器接口
public interface AdvenceMediaPlayer {
void playMp4(String fileName);
void playMp5(String fileName);
}
// 普通播放器接口
public interface MediaPlayer {
void play(String audioType, String fileName);
}
// 适配器类
public class MediaAdapter implements MediaPlayer{
private AdvenceMediaPlayer advenceMediaPlayer;
public MediaAdapter(String audioType) {
if(audioType.equalsIgnoreCase("mp4")) {
advenceMediaPlayer = new Mp4Player();
}else if(audioType.equalsIgnoreCase("mp5")) {
advenceMediaPlayer = new Mp5Player();
}
}
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("mp4")) {
advenceMediaPlayer.playMp4(fileName);
}else if(audioType.equalsIgnoreCase("mp5")) {
advenceMediaPlayer.playMp5(fileName);
}
}
}
// mp4
public class Mp4Player implements AdvenceMediaPlayer{
@Override
public void playMp4(String fileName) {
System.out.println("Mp4 player play "+fileName);
}
@Override
public void playMp5(String fileName) {
}
}
// mp5
public class Mp5Player implements AdvenceMediaPlayer{
@Override
public void playMp4(String fileName) {
}
@Override
public void playMp5(String fileName) {
System.out.println("Mp5 player play "+fileName);
}
}
// mp3
public class AudioPlayer implements MediaPlayer{
private MediaAdapter adapter;
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("mp3")) {
System.out.println("mp3 play "+fileName);
}else if(audioType.equalsIgnoreCase("mp4")
|| audioType.equalsIgnoreCase("mp5")) {
adapter = new MediaAdapter(audioType);
adapter.play(audioType, fileName);
}else {
System.out.println("Invalid mediatype"+audioType+" not support!");
}
}
}
// 测试
/* 适配器模式 */
AudioPlayer player = new AudioPlayer();
player.play("mp3", "空");
player.play("mp4", "空");
player.play("mp5", "空");
player.play("mp6", "空");