- // Target interface
- interface MediaPlayer {
- void play(String audioType, String fileName);
- }
- // Adaptee class
- class AdvancedMediaPlayer {
- void playVlc(String fileName) {
- System.out.println("Playing VLC file: " + fileName);
- }
- void playMp4(String fileName) {
- System.out.println("Playing MP4 file: " + fileName);
- }
- }
- // Adapter class
- class MediaAdapter implements MediaPlayer {
- private final AdvancedMediaPlayer advancedMediaPlayer;
- public MediaAdapter(String audioType) {
- if (audioType.equalsIgnoreCase("vlc")) {
- this.advancedMediaPlayer = new AdvancedMediaPlayer();
- } else if (audioType.equalsIgnoreCase("mp4")) {
- this.advancedMediaPlayer = new AdvancedMediaPlayer();
- } else {
- this.advancedMediaPlayer = null; // No advanced player for unsupported formats
- }
- }
- @Override
- public void play(String audioType, String fileName) {
- if (audioType.equalsIgnoreCase("vlc")) {
- advancedMediaPlayer.playVlc(fileName);
- } else if (audioType.equalsIgnoreCase("mp4")) {
- advancedMediaPlayer.playMp4(fileName);
- }
- }
- }
- // Client class
- class AudioPlayer implements MediaPlayer {
- private MediaAdapter mediaAdapter;
- @Override
- public void play(String audioType, String fileName) {
- if (audioType.equalsIgnoreCase("mp3")) {
- System.out.println("Playing MP3 file: " + fileName);
- } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
- mediaAdapter = new MediaAdapter(audioType);
- mediaAdapter.play(audioType, fileName);
- } else {
- System.out.println("Invalid media format: " + audioType);
- }
- }
- }
- // Main class to test the Adapter Design Pattern
- public class AdapterPatternExample {
- public static void main(String[] args) {
- AudioPlayer audioPlayer = new AudioPlayer();
- audioPlayer.play("mp3", "song.mp3");
- audioPlayer.play("mp4", "video.mp4");
- audioPlayer.play("vlc", "movie.vlc");
- audioPlayer.play("avi", "unsupported.avi");
- }
- }
