package net.dp.adapter.ducks; public interface Duck { public void quack(); public void fly(); }
2.定義火雞接口java
package net.dp.adapter.ducks; public interface Turkey { public void gobble(); public void fly(); }
3.定義出火雞的實現類測試
package net.dp.adapter.ducks; public class WildTurkey implements Turkey { public void gobble() { System.out.println("Gobble gobble"); } public void fly() { System.out.println("I'm flying a short distance"); } }
4.實現火雞的適配器this
package net.dp.adapter.ducks; public class TurkeyAdapter implements Duck { Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey = turkey; } public void quack() { turkey.gobble(); } public void fly() { for (int i = 0; i < 5; i++) { turkey.fly(); } } }
這樣TurkeyAdapter就能夠做爲一隻鴨子使用啦!!對象
5.測試類blog
package net.dp.adapter.ducks; public class DuckTestDrive { public static void main(String[] args) { WildTurkey turkey = new WildTurkey(); Duck turkeyAdapter = new TurkeyAdapter(turkey); testDuck(turkeyAdapter); } static void testDuck(Duck duck) { duck.quack(); duck.fly(); } }