adapter pattern


An adapter helps two incompatible interfaces, whose inner functionality should suit the need, to work together. The Adapter design pattern achieves this by converting the interface of one class into an interface expected by the clients.

Intent

  • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
  • Wrap an existing class with a new interface.
  • Match an old component to a new system

Implementation

Class Diagram of Adapter Pattern
The following example is adapted from
this post.

1
2
3
4
interface {
public void play(String type, String fileName);
}

1
2
3
4
5
6
7
// AudioPlayer.java
class AudioPlayer {
public void playAudio(String fileName) {
System.out.println("Playing. Name: "+ fileName);
}
}
1
2
3
4
5
6
7
// VideoPlayer.java
class VideoPlayer {
public void playVideo(String fileName) {
System.out.println("Playing. Name: "+ fileName);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// MyPlayer.java
class MyPlayer implements {
AudioPlayer audioPlayer = new AudioPlayer();
VideoPlayer videoPlayer = new VideoPlayer();
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("avi")){
videoPlayer.playVideo(fileName);
}else if(audioType.equalsIgnoreCase("mp3")){
audioPlayer.playAudio(fileName);
}
}
}
1
2
3
4
5
6
7
8
9
// Main.java
public class Main {
public static void main(String[] args) {
Player myPlayer = new MyPlayer();
myPlayer.play("mp3", "h.mp3");
myPlayer.play("avi", "me.avi");
}
}

Reference

Wikipedia