package shipeiqi;
public interface Duck {
public void gaga();
public void fly();
}
public interface Turkey {
public void gogo();
public void fly();
}
实现接口
public class RedDuck implements Duck {
@Override
public void gaga() {
System.out.println("Ga Ga");
}
@Override
public void fly() {
System.out.println("Fly a long distance");
}
}
public class RedTurkey implements Turkey {
@Override
public void gogo() {
System.out.println("Go Go");
}
@Override
public void fly() {
System.out.println("Fly a short distance");
}
}
实现适配器
//用户看到的是鸭子
public class TurkeyAdapter implements Duck {
private Turkey turkey;
public TurkeyAdapter(Turkey turkey){
this.turkey = turkey;
}
@Override
public void gaga() {
turkey.gogo();
}
@Override
public void fly() {
for(int i = 0;i<3;i++){
turkey.fly();//因为鸭子飞的远,所以更改一部分
}
}
}
测试
public class MainTest {
public static void main(String[] args) {
RedDuck redDuck = new RedDuck();
RedTurkey redTurkey = new RedTurkey();
Duck duckTurkey = new TurkeyAdapter(redTurkey);
duckTurkey.gaga();
duckTurkey.fly();
}
}