Java adapter design pattern

Dictionary meaning of Adapter: A device for connecting pieces of equipment that cannot be connected directly.

Java adapter design pattern comes under structural design patterns and it provides the facility of communication between two incompatible objects.

Main use of adapter design pattern is in the situations when we need an existing functionality but with some other incompatible object.

Let’s discuss adapter design pattern with below example. MediaPlayer and AdvancedMediaPlayer are two incompatible interfaces. MediaPlayer can run audio files. AdvancedMediaPlayer can run vlc and mp4 format files. MP3Player class implements MediaPlayer interface. VLCPlayer and MP4Player implements AdvancedMediaPlayer. We want MP3Player to run mp4 or some other format. We can achieve this with adapter design pattern. We will create a MediaPlayerAdapter which will be act as an adapter between MediaPlayer and AdvancedMediaPlayer.

Example

MediaPlayer.java

package com.w3spoint;
 
public interface MediaPlayer {
	public void play(String filename);
}

AdvancedMediaPlayer.java

package com.w3spoint;
 
public interface AdvancedMediaPlayer {
	public void playFile(String filename);
}

MP3Player.java

package com.w3spoint;
 
public class MP3Player implements MediaPlayer {
	@Override
	public void play(String filename) {
		System.out.println("Playing MP3 file " + filename);		
	}
}

MP4Player.java

package com.w3spoint;
 
public class MP4Player implements AdvancedMediaPlayer {
	@Override
	public void playFile(String filename) {
		System.out.println("Playing MP4 file " + filename);		
	}
}

VLCPlayer.java

package com.w3spoint;
 
public class VLCPlayer implements AdvancedMediaPlayer {
	@Override
	public void playFile(String filename) {
		System.out.println("Playing VLC file " + filename);		
	}
}

MediaPlayerAdapter.java

package com.w3spoint;
 
public class MediaPlayerAdapter implements MediaPlayer {
	 private AdvancedMediaPlayer advancedMediaPlayer;
	 public MediaPlayerAdapter(AdvancedMediaPlayer advancedMediaPlayer) {
	    this.advancedMediaPlayer = advancedMediaPlayer;
	 }
	 @Override
	 public void play(String filename) {
	   System.out.print("Using MediaPlayerAdapter - ");
	   advancedMediaPlayer.playFile(filename);
	 }
}

AdapterPatternTest.java

package com.w3spoint;
 
public class AdapterPatternTest {
	public static void main(String args[]){
	    MediaPlayer player = new MP3Player();
	    player.play("testmp3file.mp3");
	    player = new MediaPlayerAdapter(new MP4Player());
	    player.play("testmp4file.mp4");
	    player = new MediaPlayerAdapter(new VLCPlayer());
	    player.play("testvlcfile.avi");
	}
}

Output

Playing MP3 file testmp3file.mp3
Using MediaPlayerAdapter - Playing MP4 file testmp4file.mp4
Using MediaPlayerAdapter - Playing VLC file testvlcfile.avi
Content Protection by DMCA.com
Please Share