Adapter Design Pattern in Java

Adapter Design Pattern in Java

Adapter design pattern is a structural design pattern that allows two incompatible interfaces to work together. It acts as a bridge between two interfaces, making them compatible and enabling them to work seamlessly.

Key Components:

  1. Target Interface: This is the interface that the client code expects and understands.

  2. Adaptee: This is the class or interface that you want to adapt to the Target Interface.

  3. Adapter: The Adapter is a class that implements the Target Interface and wraps an instance of the Adaptee, translating calls between them.

Benefits -

  • Promotes code reusability by adapting existing components instead of rewriting them.

  • Enables collaboration between incompatible interfaces, fostering interoperability.

  • Allows the client code to work with a common interface, regardless of the underlying implementation.

Drawbacks -

  • Can introduce additional complexity if not used judiciously.

  • May result in performance overhead due to the translation between interfaces.

  • Increases the number of classes and complexity in the codebase.

Implementation of Adapter Design Pattern

Target Interface

public interface BallPen
{
    public void writeinBall(String str);
}

Adaptee Interface

This class represents the existing component with an incompatible interface.

public class GelPen
{
    GelPen(){};
    public void WriteInGel(String str)
    {
         System.out.println(str);
    }
}

This is the pen which we have got from our friend from whom we were expecting a ball pen.

Pen Adapter Class

public class PenAdapter implements BallPen
{
     GelPen pen;
     PenAdapter()
     {
         this.pen = new GelPen();
     }

    @Override
    public void writeinBall(String str)
    {
         pen.WriteInGel(str);
    }
}

Here we have created a gel pen object as per availability and started working with it but our work is supposed to be done with Ball pen as this adapter implements Ball Pen interface . So what we will do here is we will adapt the situation and will make our work with gel pen without modifying it by simply calling WriteInGel(str) method() and this is how Adapter Design Pattern works.

Assignment Work Class

In order to write any assignment we need a pen.And that's why we are using this design pattern to adapt gel-pen into ball-pen.

public class AssignmentWork
{
    BallPen pen;
    AssignmentWork(BallPen p)
    {
       this.pen = p;
    }

    public void write(String str)
    {
          pen.writeinBall(str);
    }
}

Main Class

public class Main
{
    public  static void main(String args[])
    {
         AssignmentWork assignmentWork = new AssignmentWork(new PenAdapter());
         assignmentWork.write("writing the assignment");
         return;
    }
}

Real life examples of Adapter Design Pattern:

Database Adapters, Legacy System Integration, Plug Adapters etc.