public interface Duck { public void quack(); public void fly(); } //implements实现接口 public class MallardDuck implements Duck { public void quack() { System.out.println("Quack"); } public void fly() { System.out.println("I'm flying"); } } public interface Turkey { public void gobble(); public void fly(); } //implements实现接口 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"); } } //首先,需要实现想转换成的类型接口 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(); } } } 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(); } }
《Head First 设计模式》学习笔记——适配器模式 + 外观模式,布布扣,bubuko.com
《Head First 设计模式》学习笔记——适配器模式 + 外观模式
原文:http://blog.csdn.net/huaxi1902/article/details/28102509