Explain the Adapter Pattern with an example.

Beginner

Answer

The Adapter pattern allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces.

Example:

// Existing interface
interface MediaPlayer {
    void play(String filename);
}

// Incompatible interface
interface AdvancedPlayer {
    void playVlc(String filename);
}

// Adapter
class MediaAdapter implements MediaPlayer {
    AdvancedPlayer advancedPlayer;
    
    public void play(String filename) {
        if (filename.endsWith(".vlc")) {
            advancedPlayer = new VlcPlayer();
            advancedPlayer.playVlc(filename);
        }
    }
}

Use cases:

  • Integrating third-party libraries
  • Working with legacy code
  • Making incompatible APIs work together