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 :

Image for post
Image for post

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 :

public interface MediaPlayer {

public interface MediaPackage {

Now, you can create the implementations classes :

public class MP3 implements MediaPlayer {

public class MP4 implements MediaPackage {

public class VLC implements MediaPackage {

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 {

Now, we can assemble the puzzle to use the Adapter pattern :

public class Main {

After the execution of the program, we can see the result. MP4 and VLC can be used as MediaPlayer instances via the Adapter :

Image for post
Image for post


As a bonus, you can enjoy this tutorial with a Youtube video :

Written by

Entrepreneur / Developer / Blogger / Author. In Bitcoin We Trust:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store