zoukankan      html  css  js  c++  java
  • 设计模式--适配器模式

    设计模式--适配器模式

    1 概述


    1.1 定义
    "Convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise beacause of incompatible interfaces"(将一个雷的接口转换成客户端所期待的接口,从而使原来因接口不匹配而无法再一起工作的两个类能够一起工作)
    设配器模式(Adapter Design)将一个类的接口,转换成客户期望的另一个接口。

    1.2 分类
    类设配器:通过继承被适配者的方式进行适配。
    对象设配器:如果需要多个被适配者才能进行适配,而Java不支持多继承,所以把被适配者通过组合的方式聚集起来进行适配。一般用的较多。

    1.3 应用
    如RMI中,我们调用远程传过来的对象与我们自己的类的接口不相符合,我们可以写适配器进行适配。

    2 详解


    类适配器

     1 public interface Target {
     2     void request();
     3 }
     4 
     5 public class Source {
     6     public void doSomething() {
     7         System.out.println("Source.doSomething()");
     8     }
     9 }
    10 
    11 public class Adapter extends Source implements Target {
    12     @Override
    13     public void request() {
    14         super.doSomething();
    15     }
    16 }
    17 
    18 public class Client {
    19     public static void main(String[] args) {
    20         Target target = new Adapter();
    21         target.request();
    22     }
    23 }output:
    24 Source.doSomething()

     

    对象适配者

     1 public interface Target {
     2     void request();
     3 }
     4 
     5 public class Source {
     6     public void doSomething() {
     7         System.out.println("Source.doSomething()");
     8     }
     9 }
    10 
    11 public class Source1 {
    12     public void doSomething() {
    13         System.out.println("Source1.doSomething()");
    14     }
    15 }
    16 
    17 public class Adapter implements Target {
    18     private Source source;
    19     private Source1 source1;
    20 
    21     Adapter(Source source, Source1 source1) {
    22         this.source = source;
    23         this.source1 = source1;
    24     }
    25 
    26     @Override
    27     public void request() {
    28         source.doSomething();
    29         source1.doSomething();
    30     }
    31 }
    32 
    33 public class Client {
    34     public static void main(String[] args) {
    35         Source source = new Source();
    36         Source1 source1 = new Source1();
    37         Target target = new Adapter(source, source1);
    38         target.request();
    39     }
    40 }output:
    41 Source.doSomething()
    42 Source1.doSomething()

     

  • 相关阅读:
    java基础(一)
    html脚本总结
    python编码规范以及推导式的编写
    性能测试
    IOS 单例分析
    IOS 从一个应用跳转另一个应用
    ios开发 如何在应用内获取当前周围wifi列表和强度 并实现在应用内控制wifi开关
    iOS 获取手机的型号,系统版本,软件名称,软件版本
    ios下最简单的正则,RegexKitLite
    网络编程总结(解析数据,下载文件,确认网络环境)
  • 原文地址:https://www.cnblogs.com/maying3010/p/6617672.html
Copyright © 2011-2022 走看看