0

Adapter Pattern

Provide an interface of two incompatible interface/object. Works as a bridge/mediator between two different objects.
A great application is constantly hooked into other libraries and APIs, so we implement the adapter method So that we do not experience any trouble when a third-party API or library changes its code base.

Example – Real-world examples might be a language translator or a mobile charger. A Language translator can translate English, Hindi language.
Example 2 – API method name change in API library
http://code.tutsplus.com/tutorials/design-patterns-the-adapter-pattern–cms-22262

Difference between adapter and decorator pattern is – adapter pattern make a wrapper on two incompatible objects. But decorator pattern changes the functionality of an object at runtime.

public class Moneybroker{
	
	public void payment(){
		System.out.println("moneybroker payment");
	}
	
}
public class Paypal{
	
	public void payment(){
		System.out.println("paypal payment");
	}
	
}
public interface PaymentAdaptar{
	public void pay();
}
public class MoneybrokerAdapter implements PaymentAdaptar{
	
	protected Moneybroker _Moneybroker;
	
	public MoneybrokerAdapter(Moneybroker moneybroker) {
		// TODO Auto-generated constructor stub
		_Moneybroker = moneybroker;
	}

	@Override
	public void pay() {
		// TODO Auto-generated method stub
		_Moneybroker.payment();
	}
	
}
public class PaypalAdapter implements PaymentAdaptar{
	
	protected Paypal _Paypal;
	
	public PaypalAdapter(Paypal paypal) {
		// TODO Auto-generated constructor stub
		_Paypal = paypal;
	}

	@Override
	public void pay() {
		// TODO Auto-generated method stub
		_Paypal.payment();
	}
	
}
public class MainClass {
	
	public static void main(String[] args){
		
		PaymentAdaptar adaptar = new PaypalAdapter(new Paypal());
		adaptar.pay();
		
		System.out.println("\n*****");
		
	}

}

Toufiq Mahmud

Leave a Reply

Your email address will not be published.