标签:
适配器模式定义:将一个类的接口,转换成客户期望的还有一个接口。适配器让原本接口不兼容的类能够合作无间。
简单定义:封装对象。并提供不同的接口。
简单样例:
鸭子接口:
package headfirst.adapter.ducks; public interface Duck { public void quack(); public void fly(); }
package headfirst.adapter.ducks; public class MallardDuck implements Duck { public void quack() { System.out.println("Quack"); } public void fly() { System.out.println("I'm flying"); } }
package headfirst.adapter.ducks; public interface Turkey { public void gobble(); public void fly(); }
package headfirst.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"); } }
package headfirst.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(); } } }測试:
package headfirst.adapter.ducks; 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("\nThe Duck says..."); testDuck(duck); System.out.println("\nThe TurkeyAdapter says..."); testDuck(turkeyAdapter); } static void testDuck(Duck duck) { duck.quack(); duck.fly(); } }输出:
The Turkey says... Gobble gobble I'm flying a short distance The Duck says... Quack I'm flying The TurkeyAdapter says... Gobble gobble I'm flying a short distance I'm flying a short distance I'm flying a short distance I'm flying a short distance I'm flying a short distance
版权声明:本文博主原创文章。博客,未经同意不得转载。
标签:
原文地址:http://www.cnblogs.com/hrhguanli/p/4905141.html