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

     

  • 相关阅读:
    [转] Actor生命周期理解
    [转] Linux History(历史)命令用法 15 例
    [转] CDH6 安装文章链接收集
    [转] org.scalatest.FunSuite Scala Examples
    [转] Mock以及Mockito的使用
    关于 maven 打包直接运行的 fat jar (uber jar) 时需要包含本地文件系统第三方 jar 文件的问题
    [转] flume使用(六):后台启动及日志查看
    [转] etcd 搭建与使用
    [转] 2018年最新桌面CPU性能排行天梯图(含至强处理器)
    让 Linux grep 的输出不换行
  • 原文地址:https://www.cnblogs.com/maying3010/p/6617672.html
Copyright © 2011-2022 走看看