标签:引用 interface 不同 str like 而不是 size 类适配器 ati
适配器模式:将一个类的接口转换成客户期望的另一个接口。适配器让原本接口不相融的类可以相互合作
设计:
客户使用适配器的过程:
特点:
对象适配器vs类适配器:
装饰者vs适配器:
举例:
使用新的火鸡代替鸭子,客户希望想操作鸭子一样操作火鸡
火鸡接口与鸭子接口:
1 public interface Turkey { 2 public void gobble(); 3 public void fly(); 4 } 5 6 public interface Duck { 7 public void quack(); 8 public void fly(); 9 }
创建适配器:
1 public class TurkeyAdapter implements Duck { 2 Turkey turkey; 3 TurkeyAdapter(Turkey turkey){ 4 this.turkey = turkey; 5 } 6 public void fly() { 7 for(int i=0;i<5;i++){ 8 turkey.fly(); 9 } 10 } 11 public void quack() { 12 turkey.gobble(); 13 } 14 }
客户端通过适配器像操作鸭子一样操作火鸡,而无需知道我们是通过适配器操作,更无需知道我们操作的是哪种鸭子或火鸡,因为我们是面向接口而不是实现编程
1 public class DuckTestDrive { 2 public static void main(String[] args) { 3 MallardDuck Duck = new MallardDuck(); 4 WildTurkey turkey = new WildTurkey(); 5 Duck turkeyAdapter = new TurkeyAdapter(turkey); // generate a turkey-like duck 6 turkeyAdapter.fly(); 7 turkeyAdapter.quack(); 8 } 9 }
标签:引用 interface 不同 str like 而不是 size 类适配器 ati
原文地址:http://www.cnblogs.com/HectorHou/p/5998714.html