Client에서 Target Interface를 사용하여 method를 호출함으로써 adapter에 요청을 한다.
Adapter에서는 adapter interface를 사용하여 그 요청을 adapter에 대한 하나 이상의 메소드를 호출로 변환한다.
Client에서는 호출 결과를 받긴 하지만 중간에 Adapter의 역할이 있었는지 전혀 알 수 없다.
기존의 Duck interface
public interface Duck {
public void quack();
public void fly();
}
public class MallardDuck implements Duck{
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("Quack");
}
@Override
public void quack() {
// TODO Auto-generated method stub
System.out.println("I'm flying");
}
}
public interface Turkey {
public void gobble();
public void fly();
}
public class TurkeyAdapter implements Duck{
Turkey turkey;
public TurkeyAdapter(Turkey turkey){
this.turkey=turkey;
}
@Override
public void quack() {
turkey.gobble();
}
@Override
public void fly() {
turkey.fly();
}
}
public class WildTurkey implements Turkey{
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("Gobble gobble");
}
@Override
public void gobble() {
// TODO Auto-generated method stub
System.out.println("I'm flying a short distance");
}
}
public class DuckTestDrive {
public static void main(String[] args) {
MallardDuck duck = new MallardDuck();
WildTurkey turkey = new WildTurkey();
Duck turkeyAdapter = new TurkeyAdapter(turkey);
System.out.println("The turkey says...");
turkey.gobble();
turkey.fly();
System.out.println("The Duck says...");
testDuck(duck);
System.out.println("The TurkeyAdapter says...");
testDuck(turkeyAdapter);
}
public static void testDuck(Duck duck){
duck.quack();
duck.fly();
}
}
The turkey says...
I'm flying a short distance
Gobble gobble
The Duck says...
I'm flying
Quack
The TurkeyAdapter says...
I'm flying a short distance
Gobble gobble