设计

意图

将一个类的接口转换成客户希望的另外一个接口。
适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

实现方式

媒体播放器

  1. //媒体播放
  2. public interface MediaPlayer {
  3. void play(String audioType, String fileName);
  4. }
  1. //高级媒体播放器
  2. public interface AdvancedMediaPlayer {
  3. void playVlc(String fileName);
  4. void playMp4(String fileName);
  5. }

播放器实现

  1. public class Mp4Player implements AdvancedMediaPlayer {
  2. @Override
  3. public void playVlc(String fileName) {
  4. }
  5. @Override
  6. public void playMp4(String fileName) {
  7. System.out.println("Playing mp4 file. Name: "+ fileName);
  8. }
  9. }
  1. public class VlcPlayer implements AdvancedMediaPlayer {
  2. @Override
  3. public void playVlc(String fileName) {
  4. System.out.println("Playing vlc file. Name: "+ fileName);
  5. }
  6. @Override
  7. public void playMp4(String fileName) {
  8. }
  9. }

媒体播放器

  1. //媒体播放
  2. public interface MediaPlayer {
  3. void play(String audioType, String fileName);
  4. }

适配器

  1. //MediaPlayer 接口的适配器类
  2. public class MediaAdapter implements MediaPlayer {
  3. AdvancedMediaPlayer advancedMusicPlayer;
  4. public MediaAdapter(String audioType){
  5. if(audioType.equalsIgnoreCase("vlc") ){
  6. advancedMusicPlayer = new VlcPlayer();
  7. } else if (audioType.equalsIgnoreCase("mp4")){
  8. advancedMusicPlayer = new Mp4Player();
  9. }
  10. }
  11. @Override
  12. public void play(String audioType, String fileName) {
  13. if(audioType.equalsIgnoreCase("vlc")){
  14. advancedMusicPlayer.playVlc(fileName);
  15. }else if(audioType.equalsIgnoreCase("mp4")){
  16. advancedMusicPlayer.playMp4(fileName);
  17. }
  18. }
  19. }
  1. //实现MediaPlayer接口的实体类
  2. public class AudioPlayer implements MediaPlayer {
  3. MediaAdapter mediaAdapter;
  4. @Override
  5. public void play(String audioType, String fileName) {
  6. //播放 mp3 音乐文件的内置支持
  7. if(audioType.equalsIgnoreCase("mp3")){
  8. System.out.println("Playing mp3 file. Name: "+ fileName);
  9. }
  10. //mediaAdapter 提供了播放其他文件格式的支持
  11. else if(audioType.equalsIgnoreCase("vlc")
  12. || audioType.equalsIgnoreCase("mp4")){
  13. mediaAdapter = new MediaAdapter(audioType);
  14. mediaAdapter.play(audioType, fileName);
  15. }
  16. else{
  17. System.out.println("Invalid media. "+
  18. audioType + " format not supported");
  19. }
  20. }
  21. }

客户端

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