标签:
定义:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
1 //定义鸭子接口 2 public interface Duck { 3 public void quack(); 4 public void fly(); 5 } 6 //绿头鸭 7 public class MallardDuck implements Duck{ 8 9 @Override 10 public void quack() { 11 // TODO Auto-generated method stub 12 System.out.println("duck ... quack .... quack"); 13 } 14 15 @Override 16 public void fly() { 17 // TODO Auto-generated method stub 18 System.out.println("duck ... fly ... fly"); 19 } 20 21 } 22 //定义火鸡接口 23 public interface Turkey { 24 25 public void gobble(); 26 public void fly(); 27 } 28 //实现火鸡接口 29 public class WildTurkey implements Turkey{ 30 31 @Override 32 public void gobble() { 33 // TODO Auto-generated method stub 34 System.out.println("turkey ... gobble ... gobble"); 35 } 36 37 @Override 38 public void fly() { 39 // TODO Auto-generated method stub 40 System.out.println("turkey ... fly ... fly"); 41 } 42 43 } 44 //适配器,火鸡适配鸭子 45 public class TurkeyAdapter implements Duck{ 46 47 private Turkey mTurKey = null; 48 49 public TurkeyAdapter(Turkey trukey){ 50 mTurKey = trukey; 51 } 52 @Override 53 public void quack() { 54 // TODO Auto-generated method stub 55 if(mTurKey != null) 56 mTurKey.gobble(); 57 } 58 59 @Override 60 public void fly() { 61 // TODO Auto-generated method stub 62 if(mTurKey != null) 63 mTurKey.fly(); 64 } 65 66 } 67 public class Client { 68 69 public static void main(String[] args) { 70 71 MallardDuck duck = new MallardDuck(); 72 73 WildTurkey turkey = new WildTurkey(); 74 75 Duck turkeyAdapter = new TurkeyAdapter(turkey); 76 77 testDuck(duck); 78 79 testDuck(turkeyAdapter); 80 } 81 82 static void testDuck(Duck duck){ 83 if(duck != null){ 84 duck.quack(); 85 duck.fly(); 86 } 87 } 88 }
标签:
原文地址:http://www.cnblogs.com/jaden/p/4401615.html