Design Patterns Series - Part Five: Adapter pattern

Design Patterns Series – Part Five: Adapter pattern

According to wikipedia:

In computer programming, the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface.

The adapter pattern is commonly used when there is a need to access an object through the interface which doesn’t match the one you need. This pattern is especially useful if you have a set of existing classes and you need to use them together with other ones, exposing different interface.


The purpose of this pattern is to make some objects look like something they are not. Normally, you wouldn’t use this pattern at the design stage but rather while extending an existing application, working with 3rd party libraries or tools.

Simple example using adapter pattern:
We have an existing class called ThirdPartyShape with a method ‘paintShape’ we want to move into a common interface.

package adapterpattern;

/**
 *
 * @author kris
 */

public class ThirdPartyShape {

    public void paintShape(){
        System.out.println("Painting 3rd party shape");
    }
}

Common interface in our new application:

package adapterpattern;

/**
 *
 * @author kris
 */

public interface ShinyShapeIfc {

    public void paint();
}

Example of standard shape class in our application:

package adapterpattern;

/**
 *
 * @author kris
 */

public class MyNewShinyShape implements ShinyShapeIfc{

    public void paint(){
        System.out.println("Painting brand new and shiny custom shape!");
    }
}

Adapter class used to utilize functionality of 3rd party class into our interface for painting shapes

package adapterpattern;

/**
 *
 * @author kris
 */

public class ShinyShape3rdpartyAdapter implements ShinyShapeIfc{

    private ThirdPartyShape thirdPartyShape;

    public ShinyShape3rdpartyAdapter(ThirdPartyShape tps){
        this.thirdPartyShape = tps;
    }
    /**
     * Method adapting 3rd party functionality into a common
     * interface
     */

    public void paint() {
        this.thirdPartyShape.paintShape();
    }

}

Simple proof of concept, using our shapes with existing 3rd party shapes by implementing and adapter pattern:

/**
 *
 * @author kris
 */

public class Main {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        ThirdPartyShape thirdPartyShape = new ThirdPartyShape();
        ShinyShapeIfc myOwnShinyShape = new MyNewShinyShape();
        //adapting 3rd party class into a common interface using an adapter
        ShinyShapeIfc adapted3rdPartyShape = new ShinyShape3rdpartyAdapter(thirdPartyShape);

        //object below implement common interface
        myOwnShinyShape.paint();
        adapted3rdPartyShape.paint();
    }

}

One response on “Design Patterns Series – Part Five: Adapter pattern

Leave a Reply