Let’s suppose if you’re using Mac book pro, then you’ll observe that it won’t be having USB-A ports at all. It has only USB-C ports. If you want to connect the USB port with your Macbook, you need to buy an adapter for that. It will convert the USB-A to the USB-C port.
For charging your phone, you need to connect your phone with a phone charging adapter. In India, 220 V is the power output for household purposes. So, the phone charging adapter will cover the 220 V into 9 V for phone applications.
Now we’ll see a technical example for Adapter Design Pattern. When you are writing any Java application and that Java application needs to connect to the database. People who write Java applications are not aware of the databases behind it. It may be “Oracle”, “MySQL” or “Sybase”. If a new vendor is providing a better database, then the database behind that would change. So, we aren’t aware of the database running behind. We need to write an application, using some commands and statements. he adapter class would handle those problems. Let’s suppose if we are trying to migrate from “Oracle” to “Sybase”, then the adapter class will be changed. So this would be handled by this adapter class.
public class Voltage { private int voltage; public Voltage(int v) { this.voltage = v; } public int getVolts() { return voltage; } public void setVolts(int voltage) { this.voltage = voltage; } }
public interface SocketAdapter { public Voltage get240Voltage(); public Voltage get12Voltage(); public Voltage get3VVoltage(); }
public class Socket { public Voltage getVoltage() { return new Voltage(240); //In India 240 is the default voltage } }
public class SocketAdapterImpl extends Socket implements SocketAdapter { //Using Composition for adapter pattern private Socket sock = new Socket(); private Voltage convertVolt(Voltage v, int i) { return new Voltage(v.getVolts() / i); } @Override public Voltage get240Voltage() { return sock.getVoltage(); } @Override public Voltage get12Voltage() { Voltage v = sock.getVoltage(); return convertVolt(v, 20); } @Override public Voltage get3VVoltage() { Voltage v = sock.getVoltage(); return convertVolt(v, 80); } }
public class AdapterEx { public static void main(String[] args) { SocketAdapter socketAdapter = new SocketAdapterImpl(); Voltage voltage12 = socketAdapter.get12Voltage(); System.out.println(voltage12.getVolts()); Voltage voltage3 = socketAdapter.get3VVoltage(); System.out.println(voltage3.getVolts()); Voltage voltage240 = socketAdapter.get240Voltage(); System.out.println(voltage240.getVolts()); } }
public class CivilEngineer { private HouseBuilder houseBuilder; public CivilEngineer(HouseBuilder houseBuilder) { this.houseBuilder = houseBuilder; } public House getHouse() { return this.houseBuilder.getHouse(); } public void constructHouse() { this.houseBuilder.buildBasement(); this.houseBuilder.buildStructure(); this.houseBuilder.bulidRoof(); } }