Adapter Pattern

本文通过具体的Java代码示例介绍了适配器模式的基本概念及其实现方式。适配器模式可以使得原本接口不兼容的两个类能够协同工作,文中详细展示了如何将火鸡的行为适配为鸭子的行为。

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     }

转载于:https://www.cnblogs.com/wendao/archive/2012/05/19/oth_adapter_pattern.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值