关于Java 设计模式 适配器模式 Adapter

关于Java 设计模式 适配器模式 Adapter

1、MediaPlayer.java

package com.ssm.cts.pattern.adapter;

public interface MediaPlayer {
  public void play(String audioType, String fileName);
}

2、MediaAdapter.java

package com.ssm.cts.pattern.adapter;

public class MediaAdapter implements MediaPlayer {
  AdvancedMediaPlayer advancedMusicPlayer;

  public MediaAdapter(String audioType) {
    if (audioType.equalsIgnoreCase("vlc")) {
      advancedMusicPlayer = new VlcPlayer();
    } else if (audioType.equalsIgnoreCase("mp4")) {
      advancedMusicPlayer = new Mp4Player();
    }
  }

  @Override
  public void play(String audioType, String fileName) {
    if (audioType.equalsIgnoreCase("vlc")) {
      advancedMusicPlayer.playVlc(fileName);
    } else if (audioType.equalsIgnoreCase("mp4")) {
      advancedMusicPlayer.playMp4(fileName);
    }
  }

}

3、AudioPlayer.java

package com.ssm.cts.pattern.adapter;

public class AudioPlayer implements MediaPlayer {

  MediaAdapter mediaAdapter;

  @Override
  public void play(String audioType, String fileName) {

    // 播放 mp3 音乐文件的内置支持
    if (audioType.equalsIgnoreCase("mp3")) {
      System.out.println("Playing mp3 file. Name: " + fileName);
    }
    // mediaAdapter 提供了播放其他文件格式的支持
    else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
      mediaAdapter = new MediaAdapter(audioType);
      mediaAdapter.play(audioType, fileName);
    } else {
      System.out.println("错误的文件格式. " + audioType + " format not supported");
    }
  }

}

4、AdvancedMediaPlayer.java

package com.ssm.cts.pattern.adapter;

public interface AdvancedMediaPlayer {
  public void playVlc(String fileName);

  public void playMp4(String fileName);
}

5、Mp4Player.java

package com.ssm.cts.pattern.adapter;

public class Mp4Player implements AdvancedMediaPlayer {

  @Override
  public void playVlc(String fileName) {
    // TODO Auto-generated method stub

  }

  @Override
  public void playMp4(String fileName) {
    System.out.println("Playing mp4 file. Name: "+ fileName);
  }

}

6、VlcPlayer.java

package com.ssm.cts.pattern.adapter;

public class VlcPlayer implements AdvancedMediaPlayer {

  @Override
  public void playVlc(String fileName) {
    System.out.println("Playing vlc file. Name: "+ fileName);
  }

  @Override
  public void playMp4(String fileName) {
    // TODO Auto-generated method stub

  }

}

7、Demo.java

package com.ssm.cts.pattern.adapter;

public class Demo {

  // 测试
  public static void main(String[] args) {
    AudioPlayer audioPlayer = new AudioPlayer();

    audioPlayer.play("mp3", "1.mp3");
    audioPlayer.play("mp4", "2.mp4");
    audioPlayer.play("vlc", "3.vlc");
    audioPlayer.play("avi", "4.avi");
  }

}

 

发表回复

您的电子邮箱地址不会被公开。