1.需要適配的兩個介面 2.適配器轉換介面 3.具體實現需要適配的介面的類 4.應用 5.介面應該是這樣的,鴨介面調出來 的是火雞的方法 ...
1.需要適配的兩個介面
public interface Duck { public void quack(); public void fly(); } public interface Turkey { public void gobble(); public void fly(); }
2.適配器轉換介面
//這裡是披著鴨皮的火雞
public class TurkeyAdapter implements Duck { private Turkey turkey; public TurkeyAdapter(Turkey turkey){ this.turkey=turkey; } public void quack() { // TODO Auto-generated method stub this.turkey.gobble(); } public void fly() { // TODO Auto-generated method stub turkey.fly(); } }
3.具體實現需要適配的介面的類
public class MallardDuck implements Duck{ public void quack() { System.out.println("MallardDuck quack"); } public void fly() { System.out.println("MallardDuck fly"); } } public class WildTuekey implements Turkey{ public void gobble() { // TODO Auto-generated method stub System.out.println("WildTuekey gobble"); } public void fly() { // TODO Auto-generated method stub System.out.println("WildTuekey fly"); } }
4.應用
public class App { public static void main(String[] args) { MallardDuck duck=new MallardDuck(); WildTuekey turkey=new WildTuekey(); TurkeyAdapter adapter=new TurkeyAdapter(turkey); duck.fly(); duck.quack(); adapter.fly(); adapter.quack(); turkey.fly(); turkey.gobble(); } }
5.介面應該是這樣的,鴨介面調出來 的是火雞的方法