Adapter Pattern

An Adapter pattern acts as a connector between two incompatible interfaces that otherwise cannot be connected directly. An Adapter wraps an existing class with a new interface so that it becomes compatible with the client’s interface.

The main motive behind using this pattern is to convert an existing interface into another interface that the client expects. It’s usually implemented once the application is designed.

Image result for adapter

An example we are going to use is electric power that is used in the world in which there are two types. For the US, the electric power is 110 wats and for the rest of the world, the outlet electric power is 220 wats. We are going to have an adapter that gets the power wats based on the country.

public interface WorldElectricPower {

	double output = 220;
	double connect();
}
public interface UsElectricPower {

	double output = 110;
	double connect();
}
public interface PowerConnector {

	void plugIn();
}
public class PhoneCharger implements PowerConnector {

	PowerAdapter adapter = null;
	PowerInputType powerType = null;
	
	public PhoneCharger(PowerInputType powerType){
		this.powerType = powerType;
		adapter = new PowerAdapter(powerType);
	}
	
	@Override
	public void plugIn() {
		double power = adapter.connect();
		System.out.println("charge connecting to "+powerType+" power at "+power+" wats");
	}
}
public class TV implements PowerConnector {

	PowerAdapter adapter = null;
	PowerInputType powerType = null;
	
	public TV(PowerInputType powerType){
		this.powerType = powerType;
		adapter = new PowerAdapter(powerType);
	}
	
	@Override
	public void plugIn() {
		double power = adapter.connect();
		System.out.println("tv connecting to "+powerType+" power at "+power+" wats");
	}
}

public class PowerAdapter implements WorldElectricPower, UsElectricPower{

	private PowerInputType powerType;
	
	public PowerAdapter(PowerInputType powerType){
		this.powerType = powerType;
	}

	@Override
	public double connect() {
		return (powerType!=null && powerType.equals(PowerInputType.US)) ? UsElectricPower.output : WorldElectricPower.output;
	}
}

public class StructuralDesignPatternDemo {

	public static void main(String[] args) {
		PhoneCharger usCharger = new PhoneCharger(PowerInputType.US);
		usCharger.plugIn();

		TV worldTv = new TV(PowerInputType.WORLD);
		worldTv.plugIn();
		
		TV usTv = new TV(PowerInputType.US);
		usTv.plugIn();
	}
}

Result

charge connecting to US power at 110.0 wats
tv connecting to WORLD power at 220.0 wats
tv connecting to US power at 110.0 wats

Source code in Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.