Shivam Chauhan
about 1 month ago
The Adapter Design Pattern is a structural pattern that allows objects with incompatible interfaces to work together. It acts as a bridge between two interfaces, enabling seamless integration without modifying their existing code.
In this blog, we’ll cover:
The Adapter Pattern allows a class to work with another class whose interface is incompatible. It wraps the existing interface and translates requests from one form to another, ensuring compatibility between components.
The Adapter Pattern is helpful when:
Let’s implement an Audio Player that supports different media formats (e.g., MP3, MP4, and VLC). The existing system only supports MP3 files, and we’ll use the Adapter Pattern to enable other formats.
java// Target Interface
interface MediaPlayer {
void play(String audioType, String fileName);
}
// Adaptee
class AdvancedMediaPlayer {
void playMp4(String fileName) {
System.out.println("Playing MP4 file: " + fileName);
}
void playVlc(String fileName) {
System.out.println("Playing VLC file: " + fileName);
}
}
// Adapter
class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String audioType) {
advancedMediaPlayer = new AdvancedMediaPlayer();
}
@Override
public void play(String audioType, String fileName) {
if ("mp4".equalsIgnoreCase(audioType)) {
advancedMediaPlayer.playMp4(fileName);
} else if ("vlc".equalsIgnoreCase(audioType)) {
advancedMediaPlayer.playVlc(fileName);
}
}
}
// Client
class AudioPlayer implements MediaPlayer {
@Override
public void play(String audioType, String fileName) {
if ("mp3".equalsIgnoreCase(audioType)) {
System.out.println("Playing MP3 file: " + fileName);
} else if ("mp4".equalsIgnoreCase(audioType) || "vlc".equalsIgnoreCase(audioType)) {
MediaAdapter adapter = new MediaAdapter(audioType);
adapter.play(audioType, fileName);
} else {
System.out.println("Invalid media type: " + audioType);
}
}
}
// Main Class
public class Client {
public static void main(String[] args) {
AudioPlayer player = new AudioPlayer();
player.play("mp3", "song.mp3");
player.play("mp4", "video.mp4");
player.play("vlc", "movie.vlc");
player.play("avi", "clip.avi"); // Unsupported format
}
}
plaintextPlaying MP3 file: song.mp3 Playing MP4 file: video.mp4 Playing VLC file: movie.vlc Invalid media type: avi
Here’s the UML diagram for the Audio Player example:
The Adapter Design Pattern is a powerful tool for bridging the gap between incompatible interfaces. Whether integrating legacy systems or supporting multiple APIs, this pattern ensures smooth communication between components.
Start incorporating the Adapter Pattern in your projects to enhance compatibility and maintainability!