zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    (二)、一步一步学GTK+之窗口
    phpcms v9 评论的bug.
    为discuz x2.5添加播放附件(mp4)的方法
    code::blocks + C + lua 编译环境
    C语言从声卡录音的一个demo
    泛型集合(.NET 2.0)
    VS2008对ASP.NET引用的外部JS文件不能调试
    for循环和foreach
    CSS之DIV上下左右居中
    GridView控件相关(来自互联网)
  • 原文地址:https://www.cnblogs.com/wendao/p/oth_adapter_pattern.html
Copyright © 2011-2022 走看看