Adapter Design Pattern
Adapter design pattern is used when two incompatible interfaces want to work with each other but the same is not possible due to their incompatibility. Here, and adapter is needed in between to facilitate the functioning between the two.
A very classic example of this pattern we use in our daily life. We want to charge our laptop or mobile, we need an adapter. We can’t charge them without the appropriate adapter. The reason is the need of different voltage by every electronic device. And since the home supply is around 220 volts, direct supply of that much of voltage will damage the device. Thus an adapter is needed in between for proper functioning.
In this example, we are going to implement the same solution. A laptop adapter in between the laptop and the home supply from the socket.
Voltage supply interface
package com.sks.adapter;
public interface VoltageSupply {
int provideVoltage();
}
HomeSupply class
package com.sks.adapter;
public class HomeSupply implements VoltageSupply {
@Override
public int provideVoltage() {
return 220;
}
}
ChargableDevice interface
package com.sks.adapter;
public interface ChargableDevice {
String chargeDevice(VoltageAdapter adapter);
}
Laptop class
package com.sks.adapter;
public class Laptop implements ChargableDevice {
@Override
public String chargeDevice(VoltageAdapter adapter) {
float requiredVoltage = adapter.convertVoltageTo20Volts(new HomeSupply().provideVoltage());
if (requiredVoltage == 20)
return "Laptop is successfully being charged with " + requiredVoltage + " volts.";
else
return "Laptop is not compatible with this adapter. Please change it.";
}
}
VoltageAdapter interface
package com.sks.adapter;
public interface VoltageAdapter {
float convertVoltageTo20Volts(float input);
float convertVoltageTo5Volts(float input);
}
LaptopAdapter class
package com.sks.adapter;
public class LaptopAdapter implements VoltageAdapter {
@Override
public float convertVoltageTo20Volts(float input) {
float output = 0.0f;
if(input == new HomeSupply().provideVoltage()) {
output = input / 11;
}
else {
throw new RuntimeException("This adapter only works with home supply of 220 volts.");
}
return output;
}
@Override
public float convertVoltageTo5Volts(float input) {
// TODO Auto-generated method stub
return 0;
}
}
AdapterPatternTest class
package com.sks.adapter;
public class AdapterPatternTest {
public static void main(String[] args) {
Laptop laptop = new Laptop();
VoltageAdapter adapter = new LaptopAdapter();
String message = laptop.chargeDevice(adapter);
System.out.println(message);
}
}
Output: