Adapter pattern works as a bridge between two incompatible interfaces. It converts interface A into another interface B so that interface A could be compatible with those class of interface B. A real life example could be a case of travaling to another country, in the hotel, you want to charge your mobile, but you find that the socket is absolutly not the same as the ones of your country. So now we need an adapter to charge your mobile.html
We have interfaces Duck
and Turkey
. Now we want an Adapter to convert Turkey
into Duck
, so in this way, on client side, we see only Ducks! (So turkey classes would be compatible with methods for interface Duck
)java
Duck
:public interface Duck {
public void quack();
public void fly();
}
public class GreenHeadDuck implements Duck {
@Override
public void quack() {
System.out.println("Ga Ga");
}
@Override
public void fly() {
System.out.println("I am flying a long distance");
}
}
複製代碼
Turky
:public interface Turkey {
public void gobble();
public void fly();
}
public class WildTurkey implements Turkey {
@Override
public void gobble() {
System.out.println("Go Go");
}
@Override
public void fly() {
System.out.println("I am flying a short distance");
}
}
複製代碼
To realize an adapter, we have two ways:socket
public class TurkeyAdapter implements Duck {
private Turkey turkey;
public TurkeyAdapter(Turkey turkey) {
this.turkey=turkey;
}
@Override
public void quack() {
turkey.gobble();
}
@Override
public void fly() {
turkey.fly();
}
}
複製代碼
public class TurkeyAdapter extends WildTurkey implements Duck {
@Override
public void quack() {
super.gobble();
}
@Override
public void fly() {
super.fly();
}
}
複製代碼
public class MainTest {
public static void main(String[] args) {
// WildTurkey turkey = new WildTurkey();
// Duck duck = new TurkeyAdapter(turkey);
Duck duck = new TurkeyAdapter();
duck.quack();
duck.fly();
}
}
複製代碼
So on client side, we only see a duck! But it performs like a turkey :Dide
Reprintthis