|
| 1 | +package com.example.adapterpattern; |
| 2 | + |
| 3 | +// Step 1: Target interface |
| 4 | +interface MediaPlayer { |
| 5 | + void play(String audioType, String fileName); |
| 6 | +} |
| 7 | + |
| 8 | +// Step 2: Adaptee class |
| 9 | +class MediaAdapter implements MediaPlayer { |
| 10 | + AdvancedMediaPlayer advancedMusicPlayer; |
| 11 | + |
| 12 | + public MediaAdapter(String audioType) { |
| 13 | + if (audioType.equalsIgnoreCase("vlc")) { |
| 14 | + advancedMusicPlayer = new VlcPlayer(); |
| 15 | + } else if (audioType.equalsIgnoreCase("mp4")) { |
| 16 | + advancedMusicPlayer = new Mp4Player(); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public void play(String audioType, String fileName) { |
| 22 | + if (audioType.equalsIgnoreCase("vlc")) { |
| 23 | + advancedMusicPlayer.playVlc(fileName); |
| 24 | + } else if (audioType.equalsIgnoreCase("mp4")) { |
| 25 | + advancedMusicPlayer.playMp4(fileName); |
| 26 | + } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +// Step 3: Advanced Media Player (Adaptee) |
| 31 | +interface AdvancedMediaPlayer { |
| 32 | + void playVlc(String fileName); |
| 33 | + void playMp4(String fileName); |
| 34 | +} |
| 35 | + |
| 36 | +class VlcPlayer implements AdvancedMediaPlayer { |
| 37 | + public void playVlc(String fileName) { |
| 38 | + System.out.println("Playing vlc file: " + fileName); |
| 39 | + } |
| 40 | + |
| 41 | + public void playMp4(String fileName) { |
| 42 | + // Do nothing |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +class Mp4Player implements AdvancedMediaPlayer { |
| 47 | + public void playVlc(String fileName) { |
| 48 | + // Do nothing |
| 49 | + } |
| 50 | + |
| 51 | + public void playMp4(String fileName) { |
| 52 | + System.out.println("Playing mp4 file: " + fileName); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// Step 4: Concrete class using adapter |
| 57 | +class AudioPlayer implements MediaPlayer { |
| 58 | + MediaAdapter mediaAdapter; |
| 59 | + |
| 60 | + @Override |
| 61 | + public void play(String audioType, String fileName) { |
| 62 | + if (audioType.equalsIgnoreCase("mp3")) { |
| 63 | + System.out.println("Playing mp3 file: " + fileName); |
| 64 | + } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) { |
| 65 | + mediaAdapter = new MediaAdapter(audioType); |
| 66 | + mediaAdapter.play(audioType, fileName); |
| 67 | + } else { |
| 68 | + System.out.println("Invalid media type: " + audioType); |
0 commit comments