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     }
  • 相关阅读:
    IOS基础之 (二) 面向对象思想
    Android学习笔记02-Mac下编译java代码
    常用数据库 JDBC URL 格式
    MySQL学习笔记04 插入中文时出现ERROR 1366 (HY000)
    bootstrap学习总结-06 按钮
    H2嵌入式数据库
    02 C语言指针
    页面技巧
    RequireJS进阶(二)
    RequireJS进阶(一)
  • 原文地址:https://www.cnblogs.com/wendao/p/oth_adapter_pattern.html
Copyright © 2011-2022 走看看