设计模式与范式 --- 结构型模式(适配器模式)

简介: 设计模式与范式 --- 结构型模式(适配器模式)

写在前



适配器模式的英文翻译是 Adapter Design Pattern,定义一个包装类,用于包装不兼容接口的对象。

解决问题:将不兼容的接口转换为可兼容的接口,让原本由于接口不兼容而不能一起工作的类可以一起工作。

实现方式:类适配器和对象适配器。其中,类适配器使用继承关系来实现,对象适配器使用组合关系来实现。


1.实现方式



说明:


  • ITarget 表示要转化成的接口定义
  • Adaptee 是一组不兼容ITarget接口定义的接口。
  • Adaptor 将 Adaptee 转化成一组符合 ITarget 接口定义的接口。

// 类适配器: 基于继承关系实现
public interface ITarget {
  void f1();
  void f2();
  void fc();
}
public class Adaptee {
  public void fa() { //... }
  public void fb() { //... }
  public void fc() { //... }
}
public class Adaptor extends Adaptee implements ITarget {
  public void f1() {
    //...重新实现f1()...
    super.fa();
  }
  public void f2() {
    super.fb();
  }
  //这里fc()不需要实现,直接继承自Adaptee,这是跟对象适配器最大的不同点
}
// 对象适配器:基于组合关系实现
public interface ITarget {
  void f1();
  void f2();
  void fc();
}
public class Adaptee {
  public void fa() { //... }
  public void fb() { //... }
  public void fc() { //... }
}
public class Adaptor implements ITarget {
  private Adaptee adaptee;
  public Adaptor(Adaptee adaptee) {
    this.adaptee = adaptee;
  }
  public void f1() {
    adaptee.fa(); //委托给Adaptee!!
  }
  public void f2() {
    //...重新实现f2()...
  }
  public void fc() {
    adaptee.fc();
  }
}


针对这两种实现方式,评价指标如下:


  • 不兼容接口Adaptee的个数
  • 不兼容接口Adaptee与待转化接口ITarget契合程度


在实际的开发中,到底该如何选择使用哪一种呢?


(1)若Adaptee接口个数不多,两种实现方式都可。

(2)若Adaptee 接口很多,而且 Adaptee 和 ITarget 接口定义大部分都相同,那我们推荐使用类适配器,因为 Adaptor 复用父类 Adaptee 的接口,比起对象适配器的实现方式,Adaptor 的代码量要少一些。

(3)若Adaptee 接口很多,而且 Adaptee 和 ITarget 接口定义大部分都不相同,那我们推荐使用对象适配器,因为组合结构相对于继承更加灵活。


2.应用场景



一般来说,适配器模式可以看作一种“补偿模式”,用来补救设计上的缺陷。

如果在设计初期,我们就能协调规避接口不兼容的问题,那这种模式就没有应用的机会了。


(1)封装有缺陷的接口


假设我们依赖的外部系统在接口设计方面有缺陷(比如包含大量静态方法),引入之后会影响到我们自身代码的可测试性。为了隔离设计上的缺陷,我们希望对外部系统提供的接口进行二次封装,抽象出更好的接口设计,这个时候就可以使用适配器模式了。


示例代码:

public class CD {
  //这个类来自外部sdk,我们无权修改它的代码
  public static void staticFunction1() { //... }
  public void uglyNamingFunction2() { //... }
  public void tooManyParamsFunction3(int paramA, int paramB, ...) { //... }
  public void lowPerformanceFunction4() { //... }
}
// 使用适配器模式进行重构
public class ITarget {
  void function1();
  void function2();
  void fucntion3(ParamsWrapperDefinition paramsWrapper);
  void function4();
  //...
}
// 注意:适配器类的命名不一定非得末尾带Adaptor
public class CDAdaptor extends CD implements ITarget {
  //...
  public void function1() {
     super.staticFunction1();
  }
  public void function2() {
    super.uglyNamingFucntion2();
  } 
  public void function3(ParamsWrapperDefinition paramsWrapper) {  
    super.tooManyParamsFunction3(paramsWrapper.getParamA(), ...);
  }
  public void function4() {
    //...reimplement it...
  }
}


(2)统一多个类的接口设计


某个功能的实现依赖多个外部系统(或者说类)。通过适配器模式,将它们的接口适配为统一的接口定义,然后我们就可以使用多态的特性来复用代码逻辑。


假设我们的系统要对用户输入的文本内容做敏感词过滤,为了提高过滤的召回率,我们引入了多款第三方敏感词过滤系统,依次对用户输入的内容进行过滤,过滤掉尽可能多的敏感词。


但是,每个系统提供的过滤接口都是不同的。这就意味着我们没法复用一套逻辑来调用各个系统。这个时候,我们就可以使用适配器模式,将所有系统的接口适配为统一的接口定义,这样我们可以复用调用敏感词过滤的代码。


示例代码:

public class ASensitiveWordsFilter { 
  //A敏感词过滤系统提供的接口
  //text是原始文本,函数输出用***替换敏感词之后的文本
  public String filterSexyWords(String text) {
    // ...
  }
  public String filterPoliticalWords(String text) {
    // ...
  }
}
public class BSensitiveWordsFilter  { 
  //B敏感词过滤系统提供的接口
  public String filter(String text) {
    //...
  }
}
public class CSensitiveWordsFilter { 
  //C敏感词过滤系统提供的接口
  public String filter(String text, String mask) {
    //...
  }
}
//未使用适配器模式之前的代码:代码的可测试性、扩展性不好
public class RiskManagement {
  private ASensitiveWordsFilter aFilter = new ASensitiveWordsFilter();
  private BSensitiveWordsFilter bFilter = new BSensitiveWordsFilter();
  private CSensitiveWordsFilter cFilter = new CSensitiveWordsFilter();
  public String filterSensitiveWords(String text) {
    String maskedText = aFilter.filterSexyWords(text);
    maskedText = aFilter.filterPoliticalWords(maskedText);
    maskedText = bFilter.filter(maskedText);
    maskedText = cFilter.filter(maskedText, "***");
    return maskedText;
  }
}
// 使用适配器模式进行改造
public interface ISensitiveWordsFilter { 
  //统一接口定义
  String filter(String text);
}
public class ASensitiveWordsFilterAdaptor implements ISensitiveWordsFilter {
  private ASensitiveWordsFilter aFilter;
  // 敏感词过滤
  public String filter(String text) {
    String maskedText = aFilter.filterSexyWords(text);
    maskedText = aFilter.filterPoliticalWords(maskedText);
    return maskedText;
  }
}
//...省略BSensitiveWordsFilterAdaptor、CSensitiveWordsFilterAdaptor...
//扩展性更好,更加符合开闭原则,如果添加一个新的敏感词过滤系统,这个类完全不需要改动;而且基于接口而非实现编程,代码的可测试性更好。
public class RiskManagement {
  private List<ISensitiveWordsFilter> filters = new ArrayList<>();
  public void addSensitiveWordsFilter(ISensitiveWordsFilter filter) {
    filters.add(filter);
  }
  public String filterSensitiveWords(String text) {
    String maskedText = text;
    for (ISensitiveWordsFilter filter : filters) {
      maskedText = filter.filter(maskedText);
    }
    return maskedText;
  }
}


(3)替换依赖的外部系统


当我们把项目中依赖的一个外部系统替换为另一个外部系统的时候,利用适配器模式,可以减少对代码的改动。代码实现:

// 外部系统A
public interface IA {
  void fa();
}
public class A implements IA {
  public void fa() { //... }
}
// 在我们的项目中,外部系统A的使用示例
public class Demo {
  private IA a;
  public Demo(IA a) {
    this.a = a;
  }
  //...
}
Demo d = new Demo(new A());// 将外部系统A替换成外部系统B
public class BAdaptor implemnts IA {
  private B b;
  public BAdaptor(B b) {
    this.b= b;
  }
  public void fa() {
    //...
    b.fb();
  }
}
//借助BAdaptor,Demo的代码中,调用IA接口的地方都无需改动! 只需要将BAdaptor如下注入到Demo即可。
Demo d = new Demo(new BAdaptor(new B()));


(4)兼容老版本接口


在做版本升级的时候,对于一些要废弃的接口,我们不直接将其删除,而是暂时保留,并且标注为 deprecated(强烈反对的),并将内部实现逻辑委托为新的接口实现。


这样做的好处是,让使用它的项目有个过渡期,而不是强制进行代码修改。这也可以粗略地看作适配器模式的一个应用场景。


在遍历集合容器的类 Enumeration中,对这个类进行了重构,将它改名为 Iterator 类,并且对它的代码实现做了优化。但是考虑到如果将 Enumeration 直接从 JDK2.0 中删除,那使用 JDK1.0 的项目如果切换到 JDK2.0,代码就会编译不通过。为了避免这种情况的发生,我们必须把项目中所有使用到 Enumeration 的地方,都修改为使用 Iterator 才行。


单独一个项目做 Enumeration 到 Iterator 的替换,勉强还能接受。但是,使用 Java 开发的项目太多了,一次 JDK 的升级,导致所有的项目不做代码修改就会编译报错,这显然是不合理的。


为了兼容较低版本,我们将Enumeration实现替换为直接调用Itertor代码实现:

public class Collections {
  public static Emueration emumeration(final Collection c) {
    return new Enumeration() {
      // 直接调用Itertor
      Iterator i = c.iterator();
      public boolean hasMoreElments() {
        return i.hashNext();
      }
      public Object nextElement() {
        return i.next():
      }
    }
  }
}


(5)适配不同的数据格式


前面我们讲到,适配器模式主要用于接口的适配,实际上,它还可以用在不同格式的数据之间的适配。


比如,把不同征信系统拉取的不同格式的征信数据,统一为相同的格式,方便存储与使用,再比如Arrays.asList()可以看成一种数据适配器,即将数组类型数据转化为集合类型数据。

List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");


综上,适配器模式的应用场景:


  • 封装有缺陷的接口
  • 统一多个类的接口设计
  • 替换外部依赖的类
  • 兼容老版本的接口
  • 适配不同的数据格式


3.剖析Java日志



剖析一下适配器模式在Java日志中的应用


Java 中有很多日志框架,在项目开发中,我们常常用它们来打印日志信息。


大部分日志框架都提供了相似的功能,比如按照不同级别(debug、info、warn、erro……)打印日志等,但它们却并没有实现统一的接口。比如,项目中用到的某个组件使用 log4j 来打印日志,而我们项目本身使用的是 logback。将组件引入到项目之后,我们的项目就相当于有了两套日志打印框架。


如果引入多个组件,每个组件使用的日志框架都不一样,那日志本身的管理工作就变得非常复杂。Slf4j 不仅仅提供了统一的接口定义,还提供了针对不同日志框架的适配器。对不同日志框架的接口进行二次封装,适配成统一的 Slf4j 接口定义。

// slf4j统一的接口定义
package org.slf4j;
public interface Logger {
  public boolean isTraceEnabled();
  public void trace(String msg);
  public void trace(String format, Object arg);
  public void trace(String format, Object arg1, Object arg2);
  public void trace(String format, Object[] argArray);
  public void trace(String msg, Throwable t);
  public boolean isDebugEnabled();
  public void debug(String msg);
  public void debug(String format, Object arg);
  public void debug(String format, Object arg1, Object arg2)
  public void debug(String format, Object[] argArray)
  public void debug(String msg, Throwable t);
  //...省略info、warn、error等一堆接口
}
// log4j日志框架的适配器
//Log4jLoggerAdapter实现了LocationAwareLogger接口,其中LocationAwareLogger继承自Logger接口,也就相当于Log4jLoggerAdapter实现了Logger接口。
package org.slf4j.impl;
public final class Log4jLoggerAdapter extends MarkerIgnoringBase
  implements LocationAwareLogger, Serializable {
  final transient org.apache.log4j.Logger logger;
  // log4j
  public boolean isDebugEnabled() {
    return logger.isDebugEnabled();
  }
  public void debug(String msg) {
    logger.log(FQCN, Level.DEBUG, msg, null);
  }
  public void debug(String format, Object arg) {
    if (logger.isDebugEnabled()) {
      FormattingTuple ft = MessageFormatter.format(format, arg);
      logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
    }
  }
  public void debug(String format, Object arg1, Object arg2) {
    if (logger.isDebugEnabled()) {
      FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
      logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
    }
  }
  public void debug(String format, Object[] argArray) {
    if (logger.isDebugEnabled()) {
      FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
      logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
    }
  }
  public void debug(String msg, Throwable t) {
    logger.log(FQCN, Level.DEBUG, msg, t);
  }
  //...省略一堆接口的实现...
}


综上,在开发业务系统或者开发框架、组件的时候,我们统一使用 Slf4j 提供的接口来编写打印日志的代码,具体使用哪种日志框架实现(log4j、logback……),是可以动态地指定的,只需要将相应的 SDK 导入到项目中即可。


Slf4j 不仅仅提供了从其他日志框架到 Slf4j 的适配器,还提供了反向适配器,也就是从 Slf4j 到其他日志框架的适配。我们可以先将 JCL 切换为 Slf4j,然后再将 Slf4j 切换为 log4j。经过两次适配器的转换,我们就能成功将 log4j 切换为了 logback。


4.总结与补充



代理、桥接、装饰者、适配器4种设计模式的区别


共性:都可以称为Wrapper类,即通过Wrapper类二次封装原始类。


主要区别:


  • 代理模式:在不改变原始类接口的条件下,为原始类定义有一个代理类,主要目的是访问控制,而非加强功能,这是与装饰者模式最大的不同。
  • 桥接模式:主要目的是将接口部分与实现部分分离,从而让他们可以较为容易、相对独立的改变。
  • 装饰者模式:在不改变原始类接口的情况下,对原始类进行增强,并支持多个装饰器的嵌套。
  • 适配器模式:是一种事后的补救策略。适配器提供跟原始类不同的接口,而代理模式和装饰者模式提供与原始类相同的接口。


5.参考



极客时间《设计模式之美》 ----- 王争

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
12天前
|
设计模式 Java 中间件
23种设计模式,适配器模式的概念优缺点以及JAVA代码举例
【4月更文挑战第6天】适配器模式(Adapter Pattern)是一种结构型设计模式,它的主要目标是让原本由于接口不匹配而不能一起工作的类可以一起工作。适配器模式主要有两种形式:类适配器和对象适配器。类适配器模式通过继承来实现适配,而对象适配器模式则通过组合来实现
30 4
|
3月前
|
设计模式 存储 数据库
设计模式之适配器模式
设计模式之适配器模式
|
4月前
|
设计模式 Java
Java设计模式【六】:适配器模式
Java设计模式【六】:适配器模式
14 0
|
1月前
|
设计模式 存储 安全
Java设计模式---结构型模式
Java设计模式---结构型模式
|
3月前
|
设计模式 Java 应用服务中间件
设计模式 -结构型模式_门面模式(外观模式) Facade Pattern 在开源软件中的应用
设计模式 -结构型模式_门面模式(外观模式) Facade Pattern 在开源软件中的应用
30 1
|
30天前
|
设计模式 算法 API
适配器模式:C++设计模式中的瑞士军刀
适配器模式:C++设计模式中的瑞士军刀
45 0
|
30天前
|
设计模式
设计模式之适配器模式
设计模式之适配器模式
|
1月前
|
设计模式 Java 程序员
【设计模式】适配器模式
【设计模式】适配器模式
|
3月前
|
设计模式 程序员
【设计模式】适配器模式
【1月更文挑战第27天】【设计模式】适配器模式
|
3月前
|
设计模式
设计模式-类适配器模式
设计模式-类适配器模式
12 0