适配器模式

适配器模式

适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。将一个类的接口转换成客户希望的另外一个接口。


 

适配器模式_第1张图片

1、创建媒体播放器和高级媒体播放器接口

1 public interface MediaPlayer {
2     void play(String audioType,String fileName);
3 }
MediaPlayer
1 public interface AdvanceMediaplayer {
2     void playVLC(String fileName);
3     void playMP4(String fileName);
4 }
AdvanceMediaplayer

2、高级播放器的2个实现类

 1 public class MP4Player implements  AdvanceMediaplayer {
 2     @Override
 3     public void playVLC(String fileName) {
 4 
 5     }
 6 
 7     @Override
 8     public void playMP4(String fileName) {
 9         System.out.println("Playing mp4 file. Name:"+fileName);
10     }
11 }
MP4Player
 1 public class VLCPlayer implements  AdvanceMediaplayer{
 2     @Override
 3     public void playVLC(String fileName) {
 4         System.out.println("Playing vlc file. Name:" + fileName);
 5     }
 6 
 7     @Override
 8     public void playMP4(String fileName) {
 9 
10     }
11 }
VLCPlayer

3、创建适配器

 1 public class MediaAdapter implements MediaPlayer {
 2     AdvanceMediaplayer advanceMediaplayer;
 3 
 4     public MediaAdapter(String audioType){
 5         if (audioType.equalsIgnoreCase("vlc")){
 6             advanceMediaplayer = new VLCPlayer();
 7         }else if(audioType.equalsIgnoreCase("mp4")){
 8             advanceMediaplayer = new MP4Player();
 9         }
10     }
11     @Override
12     public void play(String audioType, String fileName) {
13         if(audioType.equalsIgnoreCase("vlc")){
14             advanceMediaplayer.playVLC(fileName);
15         }else if(audioType.equalsIgnoreCase("mp4")){
16             advanceMediaplayer.playMP4(fileName);
17         }
18     }
19 }
MediaAdapter

4、媒体播放器的实现类

 1 public class AudioPlayer implements MediaPlayer {
 2     private MediaAdapter mediaAdapter;
 3     @Override
 4     public void play(String audioType, String fileName) {
 5         if(audioType.equalsIgnoreCase("mp3")){
 6             System.out.println("Playing mp3 file. Name: "+ fileName);
 7         }else if(audioType.equalsIgnoreCase("vlc")
 8         ||audioType.equalsIgnoreCase("mp4")){
 9             mediaAdapter = new MediaAdapter(audioType);
10             mediaAdapter.play(audioType,fileName);
11         }else{
12             System.out.println("Invalid media."+
13                     audioType + "format not supported");
14         }
15     }
16 }
AudioPlayer

5、测试类

 1 public class AdapterPatternDemo {
 2     public static void main(String[] args) {
 3         AudioPlayer audioPlayer = new AudioPlayer();
 4 
 5         audioPlayer.play("mp3", "beyond the horizon.mp3");
 6         audioPlayer.play("mp4", "alone.mp4");
 7         audioPlayer.play("vlc", "far far away.vlc");
 8         audioPlayer.play("avi", "mind me.avi");
 9     }
10 }
AdapterPatternDemo

6、结果

1 Playing mp3 file. Name: beyond the horizon.mp3
2 Playing mp4 file. Name:alone.mp4
3 Playing vlc file. Name:far far away.vlc
4 Invalid media.aviformat not supported
结果

 

 

你可能感兴趣的:(适配器模式)