Adapter Design Pattern

Adapter Design Pattern.


Adapter Design Pattern is used to make in-compatible interfaces compatible.



Adapter Design Pattern Example In Java.

We have Socket which charges Apple Mobile and we want same Socket to be used for Samsung Mobile as well, We will make socket compatible.  

Apple.java
interface Apple{
 void charge();
}
AppleImpl.java
class AppleImpl implements Apple{
 
 @Override
 public void charge() {
  System.out.println("Charging Apple Mobile...");
 }
}
SocketForAppleMobile.java
class SocketForAppleMobile{
 public static void charge(Apple apple){
  System.out.println("It is not correct but say: Start Electricity at home");
  apple.charge();
  System.out.println("It is not correct but say: End Electricity at home");
 }
}
Samsung.java
interface Samsung{
 void charge();
}
SamsumgImpl.java
class SamsumgImpl implements Samsung{
 
 @Override
 public void charge() {
  System.out.println("Charging Samsung Mobile...");
 }
}
AppleSamsungAdapter.java
class AppleSamsungAdapter implements Apple{
 
 private Samsung samsung;
 
 public AppleSamsungAdapter(Samsung samsung) {
  this.samsung = samsung;
 }
 
 @Override
 public void charge() {
  samsung.charge();
 }
}
AdapterDesignPattern.java
public class AdapterDesignPattern {

 public static void main(String[] args) {
  Apple appleMobile = new AppleImpl();
  SocketForAppleMobile.charge(appleMobile);
  
  Samsung samsungMobile = new SamsumgImpl();
  //SocketForAppleMobile.charge(samsungMobile); //It will not accept Samsung charger
  
  AppleSamsungAdapter appleSamsungMobile = new AppleSamsungAdapter(samsungMobile);
  SocketForAppleMobile.charge(appleSamsungMobile); //It will charge now..
 }
}

Decorator Design Pattern

When to use Builder design pattern

Observer Design Pattern

Command Design Pattern

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment