适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
普通音频播放器设备只能播放 mp3 文件,通过使用一个更高级的音频播放器来播放 vlc 和 mp4 文件。
public interface MediaPlayer {
void play(String type, String name);
}
public interface AdvancedMediaPlayer {
void playMp4(String name);
void playVlc(String name);
}
public class AdvancedPlayer implements AdvancedMediaPlayer {
@Override
public void playMp4(String name) {
System.out.println("play mp4 " + name);
}
@Override
public void playVlc(String name) {
System.out.println("play vlc " + name);
}
}
public class MediaAdapter extends AdvancedPlayer implements MediaPlayer {
@Override
public void play(String type, String name) {
if ("mp3".equals(type)){
System.out.println("play mp3 " + name);
}else if ("mp4".equals(type)){
super.playMp4(name);
}else if ("vlc".equals(type)){
super.playVlc(name);
}else {
System.out.println("not supported");
}
}
}
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");
audioPlayer.play("avi", "mind me.avi");
}
}
public interface MediaPlayer {
void play(String type, String name);
}
public interface AdvancedMediaPlayer {
void playMp4(String name);
void playVlc(String name);
}
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playMp4(String name) {
System.out.println("play mp4 " + name);
}
@Override
public void playVlc(String name) {
}
}
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playMp4(String name) {
}
@Override
public void playVlc(String name) {
System.out.println("play vlc " + name);
}
}
public class MediaAdapter implements MediaPlayer{
private AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String type){
if ("mp4".equals(type)){
advancedMediaPlayer = new Mp4Player();
}else if ("vlc".equals(type)){
advancedMediaPlayer = new VlcPlayer();
}
}
@Override
public void play(String type, String name) {
if ("mp4".equals(type)){
advancedMediaPlayer.playMp4(name);
}else if ("vlc".equals(type)){
advancedMediaPlayer.playVlc(name);
}
}
}
public class AudioPlayer implements MediaPlayer{
// 创建适配器
private MediaAdapter mediaAdapter;
@Override
public void play(String type, String name) {
if ("mp3".equals(type)){
System.out.println("play mp3 " + name);
}else if ("mp4".equals(type) || "vlc".equals(type)){
mediaAdapter = new MediaAdapter(type);
mediaAdapter.play(type,name);
}else {
System.out.println("not supported");
}
}
}
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");
audioPlayer.play("avi", "mind me.avi");
}
}