Saturday, 23 April 2016

Adapter design pattern

Adapter design pattern

It converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.


There are 2 kinds of adapters
1.     Object Adapters
2.     Class Adapters


Object adapters work over composition. They have a Has-A relationship with the adaptee.



Class adapters work over inheritance. They have a Is-A relationship with the adaptee.



Let you have imported a laptop from United States. Now you want to plug it to a Indian power socket.

public interface IUnitedStatesAppliance {
     
      public void loadPower();

}

public class LaptopFromUSA implements IUnitedStatesAppliance{

      @Override
      public void loadPower() {
            System.out.println("Charging the laptop from United States");
      }

}

public interface I_US_IndiaAdapter {
     
      public void charge();

}

public class ObjectAdapter implements I_US_IndiaAdapter {
     
      private IUnitedStatesAppliance appliance;

      public ObjectAdapter(IUnitedStatesAppliance appliance) {
            super();
            this.appliance = appliance;
      }

      @Override
      public void charge() {
            appliance.loadPower();
      }

}

public class ClassAdapter extends LaptopFromUSA implements I_US_IndiaAdapter {

      @Override
      public void charge() {
            this.loadPower();
      }

}

public class MainClass {

      public static void main(String[] args) {
            I_US_IndiaAdapter objectAdapter = new ObjectAdapter(new LaptopFromUSA());
            System.out.println("Using Object Adapter to charge");
            objectAdapter.charge();
            I_US_IndiaAdapter classAdapter = new ClassAdapter();
            System.out.println("Using Class Adapter to charge");
            classAdapter.charge();
      }

}

Result:

Using Object Adapter to charge
Charging the laptop from United States
Using Class Adapter to charge
Charging the laptop from United States

Adapter for a Java convertor


The adapter should handle all unmapped functions from caller to adaptee.

E.g. as in above, it should handle the remove function from iterator which is not supported in the legacy Enumeration interface. Since the enumeration is a read-only interface, the method is not supported. So it’s better to throw a exception from the adapter. The remove() function from Iterator supports an UnsupportedOpertaionException.


Code link : https://github.com/sksumit1/DesignPatterns

No comments:

Post a Comment