Implement the Adapter Design Pattern in Java
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem with a given context in software design. In that new serie of articles, you’re going to discover how to implement some of the most known design patterns in Java. To start the serie, you’re going to study the Adapter Design Pattern.
The Adapter Design Pattern is part of structural patterns. It allows the interface of an existing class to be used as another interface. In summary, an adapter helps two incompatible interfaces to work together. To implement the Adapter Design Pattern in Java, we choose the following example :
Here, we have two incompatible interfaces : MediaPlayer and MediaPackage. MP3 class is an implementation of the MediaPlayer interface and we have VLC and MP4 as implementations of the MediaPackage interface. We want to use MediaPackage implementations as MediaPlayer instances. So, we need to create an adapter to help to work with two incompatible classes.
The Adapter will be named FormatAdapter and must implement the MediaPlayer interface. Furthermore, the FormatAdapter class must have a reference to MediaPackage, the incompatible interface.
This is the code for the two interfaces :
MediaPlayer.java
public interface MediaPlayer { void play(String filename); }
MediaPackage.java
public interface MediaPackage { void playFile(String filename); }
Now, you can create the implementations classes :
MP3.java
public class MP3 implements MediaPlayer { @Override public void play(String filename) { System.out.println("Playing MP3 File " + filename); } }
MP4.java
public class MP4 implements MediaPackage { @Override public void playFile(String filename) { System.out.println("Playing MP4 File " + filename); } }
VLC.java
public class VLC implements MediaPackage { @Override public void playFile(String filename) { System.out.println("Playing VLC File " + filename); } }
Here, we want to use VLC and MP4 instances as MediaPlayer instances. So, we need and adapter. This is the code of the FormatAdapter :
public class FormatAdapter implements MediaPlayer { private MediaPackage media; public FormatAdapter(MediaPackage m) { media = m; } @Override public void play(String filename) { System.out.print("Using Adapter --> "); media.playFile(filename); } }
Now, we can assemble the puzzle to use the Adapter pattern :
public class Main { public static void main(String[] args) { MediaPlayer player = new MP3(); player.play("file.mp3"); player = new FormatAdapter(new MP4()); player.play("file.mp4"); player = new FormatAdapter(new VLC()); player.play("file.avi"); } }
After the execution of the program, we can see the result. MP4 and VLC can be used as MediaPlayer instances via the Adapter :
Bonus
As a bonus, you can enjoy this tutorial with a Youtube video :
Leave a Reply
You must be logged in to post a comment.