Junior — Middle
Can you give an example of using the Adapter pattern in programming?
sobes.tech AI
Answer from AI
The Adapter pattern is used to convert the interface of a class into another interface that the client expects. This allows working with incompatible interfaces without changing existing code.
Example in Java:
// Interface expected by the client
interface MediaPlayer {
void play(String audioType, String fileName);
}
// Class with incompatible interface
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 that converts the interface
class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer = new AdvancedMediaPlayer();
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")) {
advancedMusicPlayer.playVlc(fileName);
} else if(audioType.equalsIgnoreCase("mp4")) {
advancedMusicPlayer.playMp4(fileName);
}
}
}
// Client code
class AudioPlayer implements MediaPlayer {
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();
mediaAdapter.play(audioType, fileName);
} else {
System.out.println("Invalid media type: " + audioType);
}
}
}
In this example, AudioPlayer uses MediaAdapter to play formats it does not support directly.