Adapter

作者: 93张先生 | 来源:发表于2020-09-15 09:31 被阅读0次

适配器模式

An adapter convert the interface of a class into another interface clients expect. It lets classes work together that couldn’t otherwise because of incompatible interfaces.

适配器将一个接口,转化为自己期望的接口;使不兼容的接口可以同时工作。

组件

  • 目标接口( Target ):调用者能够直接使用的接口。
  • 需要适配的类( Adaptee ): 一般情况下, Adaptee 类中有真正的业务逻辑,但是其接口不能被调用者直接使用。
  • 适配器( Adapter): Adapter 实现了 Target 口,并包装了一个 Adaptee 对象。 Adapter 在实现 Target 接口中的方法时,会将调用委托给 Adaptee 对象的相关方法,由 Adaptee完成具体的业务。

UML

image.png
image.png

场景

mybatis 日志采用适配器模式,适配了 slf4j、log4j 等多个日志框架;

Log

目标接口,供客户端调用使用。

public interface Log {

  boolean isDebugEnabled();

  boolean isTraceEnabled();

  void error(String s, Throwable e);

  void error(String s);

  void debug(String s);

  void trace(String s);

  void warn(String s);

}

Logger

需要适配的类( Adaptee ),java.util.logging.Logger 日志

public class Logger {
    public void log(Level level, String msg) {
        if (!isLoggable(level)) {
            return;
        }
        LogRecord lr = new LogRecord(level, msg);
        doLog(lr);
    }
}

Jdk14LoggingImpl

适配器 Adapter 适配了 java.util.logging 接口

public class Jdk14LoggingImpl implements Log {

  // 底层封装的 java.util.logging.Logger 对象
  private final Logger log;

  // 通过 logConstructor.newInstance(logger) 初始化 java.util.logging.Logger 对象; logger 为调用 log 日志的类名称
  public Jdk14LoggingImpl(String clazz) {
    log = Logger.getLogger(clazz);
  }

  @Override
  public boolean isDebugEnabled() {
    return log.isLoggable(Level.FINE);
  }

  @Override
  public boolean isTraceEnabled() {
    return log.isLoggable(Level.FINER);
  }

  @Override
  public void error(String s, Throwable e) {
    log.log(Level.SEVERE, s, e);
  }

  @Override
  public void error(String s) {
    log.log(Level.SEVERE, s);
  }

  @Override
  public void debug(String s) {
    log.log(Level.FINE, s);
  }

  @Override
  public void trace(String s) {
    log.log(Level.FINER, s);
  }

  @Override
  public void warn(String s) {
    log.log(Level.WARNING, s);
  }

}

Client

外部调用使用 Log 对象

public Class Client{
  public static void main(String[] args) {
   //  需要适配的类
    Log adaptee = new org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl();
   // 适配器
    Log log = new Jdk14LoggingImpl(adaptee.class.getName());
    log.info("--------finsh-----------");
  }
}

相关文章

网友评论

    本文标题:Adapter

    本文链接:https://www.haomeiwen.com/subject/gvyoektx.html