DEV Community

Dev Cookies
Dev Cookies

Posted on

πŸ“ Day Six: Adapter Design Pattern in Java

πŸ” What is the Adapter Pattern?

The Adapter Pattern allows incompatible classes to work together by converting the interface of one class into an interface expected by the client.


βœ… When Should You Use It?

  • When you want to reuse an existing class but its interface doesn’t match what your code expects.
  • When you want to create a bridge between legacy code and modern systems.
  • When you want to avoid modifying source code of existing (3rd-party or legacy) classes.

🧠 Real-World Analogy

Imagine you’re traveling from India to the USA, and you want to plug in your charger πŸͺ«. But the sockets don’t match β€” so you use a socket adapter. It converts the plug type so your charger can still work!


🧱 Structure

+--------------------+      +----------------------+
|      Client        |----->|      Target          |
+--------------------+      +----------------------+
                                  ^  
                                  |
                         +-------------------+
                         |     Adapter       |
                         +-------------------+
                                  |
                                  v
                          +---------------+
                          | Adaptee       |
                          +---------------+
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Example: Media Player Adapter

Let’s say you have a MediaPlayer interface that supports .mp3 files, but now you want to add support for .vlc, .mp4 using an AdvancedMediaPlayer. The interfaces don’t match β€” so we’ll use an Adapter.


βœ… 1. Target Interface

public interface MediaPlayer {
    void play(String audioType, String fileName);
}
Enter fullscreen mode Exit fullscreen mode

βœ… 2. Adaptee Class (Incompatible Interface)

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

public class VlcPlayer implements AdvancedMediaPlayer {
    public void playVlc(String fileName) {
        System.out.println("Playing vlc file: " + fileName);
    }

    public void playMp4(String fileName) {
        // Do nothing
    }
}

public class Mp4Player implements AdvancedMediaPlayer {
    public void playMp4(String fileName) {
        System.out.println("Playing mp4 file: " + fileName);
    }

    public void playVlc(String fileName) {
        // Do nothing
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… 3. Adapter Class

public class MediaAdapter implements MediaPlayer {
    AdvancedMediaPlayer advancedMediaPlayer;

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

    public void play(String audioType, String fileName) {
        if (audioType.equalsIgnoreCase("vlc")) {
            advancedMediaPlayer.playVlc(fileName);
        } else if (audioType.equalsIgnoreCase("mp4")) {
            advancedMediaPlayer.playMp4(fileName);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… 4. Concrete Target Class (Using the Adapter)

public class AudioPlayer implements MediaPlayer {
    MediaAdapter mediaAdapter;

    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 + " not supported.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’» Client Code

public class AdapterDemo {
    public static void main(String[] args) {
        AudioPlayer audioPlayer = new AudioPlayer();

        audioPlayer.play("mp3", "song.mp3");
        audioPlayer.play("mp4", "movie.mp4");
        audioPlayer.play("vlc", "concert.vlc");
        audioPlayer.play("avi", "series.avi");
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Output

Playing mp3 file: song.mp3
Playing mp4 file: movie.mp4
Playing vlc file: concert.vlc
Invalid media format: avi not supported.
Enter fullscreen mode Exit fullscreen mode

🎯 Benefits

βœ… Promotes code reusability

βœ… Acts as a bridge between legacy and new systems

βœ… Adds flexibility without modifying existing classes

βœ… Helps follow the Single Responsibility Principle


πŸ”Œ Java Libraries Using Adapter

  • java.util.Arrays#asList() β€” wraps an array into a List
  • javax.xml.bind.annotation.adapters.XmlAdapter β€” to map between XML and Java objects

🧠 Summary Table

Aspect Description
Pattern Type Structural
Problem Solved Interface incompatibility
Key Benefit Reusability & flexibility
Common Use Cases Integrating with 3rd party libraries, supporting legacy systems

πŸ—ΊοΈ UML Diagram (Text Format)

+--------------------+
|   MediaPlayer      | <---------+
+--------------------+           |
| +play(type, name)  |           |
+--------------------+           |
         ^                       |
         |                       |
+----------------+        +---------------------+
|  AudioPlayer    |        |   MediaAdapter      |
+----------------+        +---------------------+
                          | -AdvancedMediaPlayer |
                          | +play(...)           |
                          +---------------------+
                                   |
                     +--------------------------+
                     | VlcPlayer     Mp4Player  |
                     +--------------------------+
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Pro Tip: The Adapter pattern is often used when integrating with third-party APIs whose interface you cannot change.


πŸš€ Up Next for Day 7: Let’s keep the streak going! Want to explore:

  • Facade
  • Chain of Responsibility
  • State

Let me know what you’re feeling next, and I’ll brew the next blog for you!

Top comments (0)