Adapter Pattern

The Adapter Pattern converts the interface of a class into another interface the clients expect.
Adapter lets classes work together that couldnot otherwise beause of incompatible interfaces.

 1 interface Duck {
 2     public void quack();
 3     public void fly();
 4 }
 5 
 6 interface Turkey {
 7     public void gobble();
 8     public void fly();
 9 }
10 
11 class MallardDuck implements Duck {
12     public void quack() {
13         System.out.println("Quack");
14     }
15     public void fly() {
16         System.out.println("fly");
17     }
18 }
19 
20 class WildTurkey implements Turkey {
21     public void gobble() {
22         System.out.println("Gobble gobble");
23     }
24 
25     public void fly() {
26         System.out.println("im flying a short distance");
27     }
28 }
29 
30 class TurkeyAdapter implements Duck {
31     Turkey turkey;
32     
33     public TurkeyAdapter(Turkey turkey) {
34         this.turkey = turkey;
35     }
36 
37     public void quack() {
38         turkey.gobble();
39     }
40 
41     public void fly() {
42         for(int i=0;i < 5;i++) {
43             turkey.fly();
44         }
45     }
46 }
47 
48 
49     public static void main(String[] args) {
50         MallardDuck duck = new MallardDuck();
51         
52         WildTurkey turkey = new WildTurkey();
53         Duck turkeyAdapter = new TurkeyAdapter(turkey);
54         
55         System.out.println("the turkey says ");
56         turkey.gobble();
57         turkey.fly();
58         
59         System.out.println("the duck says ");
60         testDuck(duck);
61         
62         System.out.println("the turkeyAdatper says ");
63         testDuck(turkeyAdapter);
64     }
65     
66     static void testDuck(Duck duck) {
67         duck.quack();
68         duck.fly();
69     }
posted @ 2012-05-19 21:42  wen_dao_  阅读(143)  评论(0编辑  收藏  举报