In this tutorial I am going to explain about the adapter design pattern as part of the design patterns in Java series. Adapter design pattern is one of the structural design pattern because adapter design deals with how we make / structure an object. The primary problem this pattern trying to solve is to make it work two in-compatible interfaces. I think this gives the reason behind the term “adapter”.
There are two types of adapter design patterns:
- Class Adapter : This type uses the Java inheritance to extend the class and then implement the adapter interface.
- Object Adapter : This uses the Java composition where Adapter contains the source object.
In the below example I have used both the types of adapter pattern for your reference. I have taken the simple example of PowerGrid where the voltage is coming with high volume, I am using an adapter to convert that into lower levels. Note that this is very simple and concept remains the same even if you implement in the real time.
PowerGrid.java
class PowerGrid { public int getPower() { return 1000; } }
PowerAdapter.java
interface PowerAdapter { int get10V(); int get50V(); int get100V(); }
PowerAdapterClassImpl.java
class PowerAdapterClassImpl extends PowerGrid implements PowerAdapter { @Override public int get10V() { return (getPower() / 100); } @Override public int get50V() { return (getPower() / 20); } @Override public int get100V() { return (getPower() / 10); } }
PowerAdapterObjectImpl.java
class PowerAdapterObjectImpl implements PowerAdapter { private PowerGrid grid; @Override public int get10V() { return (grid.getPower() / 100); } @Override public int get50V() { return (grid.getPower() / 20); } @Override public int get100V() { return (grid.getPower() / 10); } }
AdapterDesignPatternExample.java
public class AdapterDesignPatternExample { public static void main(String args[]) { PowerAdapter classAdapter = new PowerAdapterClassImpl(); System.out.println(classAdapter.get100V()); System.out.println(classAdapter.get50V()); System.out.println(classAdapter.get10V()); PowerAdapter objectAdapter = new PowerAdapterObjectImpl(); System.out.println(objectAdapter.get100V()); System.out.println(objectAdapter.get50V()); System.out.println(objectAdapter.get10V()); } }
I hope this tutorial would have provided you very basic example and illustration to implement the adapter design pattern. If you have any interesting example for the adapter design pattern, please share with us in the comments section.