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()

     

  • 相关阅读:
    看过设计模式第一章的心得
    支付宝支付过程填坑
    C# 合并只要有交集的所有集合
    C#中的反射 Reflection
    动态更改配置文件
    六种弹窗
    Respone弹窗
    Aspose是一个很强大的控件,可以用来操作word,excel,ppt等文件
    使用ECharts报表统计公司考勤加班,大家加班多吗?
    排污许可管理条例-中华人民共和国国务院令第736号
  • 原文地址:https://www.cnblogs.com/maying3010/p/6617672.html
Copyright © 2011-2022 走看看