Adapter Pattern with Composition

Adapter pattern makes two incompatible interfaces to work together. These Incompatible interfaces are not designed and developed for one another, and assuming they have evolved separately.

Adapter Pattern can be implemented using any of the below.

  1. Inheritance
  2. Composition

Implementing Adapter pattern with Composition

In below example NewArithmetic and Arithmetic are classes, which are incompatible. And they have been designed separately, and one is not designed for another.

Now ArithmeticAdapter is implemented to make NewArithmetic and Arithmetic classes, compatible with each other.

Here ArithmeticAdapter contains Adaptee, i..e NewArithmetic

public class NewArithmetic
{
    public float add_values(float val1, float val2)
    {
        return val1+val2;
    }

    public float sub_values(float val1, float val2)
    {
        return val1-val2;
    }
}

public class ArithmeticAdapter{
    private NewArithmetic obj;

    public ArithmeticAdapter()
    {
        obj = new NewArithmetic();
    }

    public int add_adptr(int val1, int val2)
    {
        return (int)obj.add_values(val1,val2);
    }

    public int sub_adptr(float val1, float val2)
    {
        return (int)obj.sub_values(val1,val2);
    }
}

public class Arithmetic
{
    public void add(int val1,int val2)
    {
        System.out.println("Added Result:"+new ArithmeticAdapter().add_adptr(val1, val2));
    }

    public void sub(int val1,int val2)
    {
        System.out.println("Subtraction Result:"+new ArithmeticAdapter().sub_adptr(val1, val2));
    }
}

public class AdapterComposition {
    public static void main(String[] args) {
        Arithmetic obj = new Arithmetic();

        obj.add(23, 42);
        obj.sub(46, 21);
    }

}

Output:
Added Result:65
Subtraction Result:25

You may also like to read: Adapter Pattern with Inheritance