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     }
  • 相关阅读:
    干货分享:路由与交换详解大全!
    基于ASCII字符集对比
    css文字两端对齐
    软件版本号(BETA、RC、ALPHA、Release、GA等)
    install和update区别
    Blazor入坑指南
    解决Electron7.0.0的坑,cnpm install electron 安装失败的问题
    Linux查看CPU和内存使用情况
    位运算符在JS中的妙用
    centos7通过yum安装mysql
  • 原文地址:https://www.cnblogs.com/wendao/p/oth_adapter_pattern.html
Copyright © 2011-2022 走看看