适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。
思考: 通常是适配器通过组合的方式将下层组件和上层组件结合在一起, 然后上层组件使用适配器的相应方法来完成下层组件功能被调用的过程.
package day0317.AdapterPattern;
import java.util.Objects;
public class AdapterPatternDemo{
// 客户端程序员
public static void main(String[] args){
// find a adapter
MediaAdapter mediaAdapter = new MediaAdapter("mp4");
// find a adapter
MediaAdapter vlcMediaAdapter = new MediaAdapter("vlc");
// find player
AudioPlayer audioPlayer = new AudioPlayer();
// plug wire in
audioPlayer.setAdapter(vlcMediaAdapter);
audioPlayer.play("让她降落.vlc");
}
}
interface AdvancedMediaPlayer{
void playVlc(String vlcFile);
void playMp4(String vlcFile);
void play(String file);
}
/**
* 有两个播放器,实现了高级媒体播放器的接口
*/
class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String vlcFile){ System.out.println("Playing: " + vlcFile); }
@Override
public void playMp4(String mp4){ throw new RuntimeException("Unsupported media type"); }
@Override
public void play(String file){
String extended = file.substring(file.lastIndexOf(".") + 1);
if ("vlc".equalsIgnoreCase(extended)) { this.playVlc(file); }
else { throw new RuntimeException("Unsupported media type"); }
}
}
/**
* 媒体播放器接口
*/
interface MediaPlayer{
void play(String file);
}
class AudioPlayer implements MediaPlayer {
MediaAdapter adapter;
public void setAdapter(MediaAdapter adapter){
this.adapter = adapter;
}
@Override
public void play(String file){
adapter.play(file);
}
}
class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String mediaType){
Objects.requireNonNull(mediaType);
if (mediaType.equalsIgnoreCase("mp4")) {
this.advancedMediaPlayer = new Mp4Player();
} else if (mediaType.equalsIgnoreCase("vlc")){
this.advancedMediaPlayer = new VlcPlayer();
}
}
@Override
public void play(String file){
Objects.requireNonNull(file);
advancedMediaPlayer.play(file);
}
}
package day0317.AdapterPattern;
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String vlcFile){
throw new RuntimeException("Unsupported media type");
}
@Override
public void playMp4(String MP4){
System.out.println("Playing: " + MP4);
return;
}
@Override
public void play(String file){
String extended = file.substring(file.lastIndexOf(".") + 1);
if ("mp4".equalsIgnoreCase(extended)) {
this.playMp4(file);
} else {
throw new RuntimeException("Unsupported media type");
}
}
}