Follow treslines by email clicking Here!

Friday, August 22, 2014

Programming Design Pattern - Adapter Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Adapter design pattern in action. The Adapter design pattern is a very useful programming design pattern whenever you need to ensure communication between incompatible interfaces, classes or objects.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Adapter Pattern

Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.

The example

In our example we will see, how we could adapt incompatible interfaces so that they can interact together. We will connect a  rounded 3-pins plug with a rectangular 2-pins plug.

Incompatible Classes

The classes to adapt.

public class CylinderSocket {
    public CylinderPin cylinderPin;
    public CylinderSocket(){
        this.cylinderPin=new CylinderPin("corrent", "neutro", "terra");
public class RectangularPlug {//ADAPTEE
    public String corrente;
    public String neutro;

    public String getPower() {
        return "power on!";

The Adapter

To be able to adapt something, first of all we must define the common interface between at least two classes/objects.

public interface Plugable { // "TARGET" INTERFACE
    public String getPower();

The Test

Finally, let's test our adapter which will connect a rounded plug with a rectangular plug.

public class Client {
    public static void main(String[] args) {
        // Rounded plug with 3 pins with rectangular plug with 2 pins
        CylinderSocket cylinderSocket = new CylinderSocket();
        // Client knows only the interface
        Plugable plugable = new PlugAdapter(cylinderSocket);
        // see if connection works

That's all! Hope you like it!

No comments:

Post a Comment