适配器模式在开源代码中的应用
16lz
2021-01-22
适配器模式的作用:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。
开源代码中,哪些地方用到了适配器模式呢?
案例一
java.util.Enumeration JDK 1.0 提供用于遍历容器类的接口,但是一个公认的设计失误,所以 JDK 1.2 对其进行了重构,新增 Iterator 接口去迭代容器类。
JDK 为了保证向后兼容,就在容器工具类 java.util.Collections 的 enumeration 方法中使用了适配器模式,用 Collection#iterator() 构造 Enumeration 对象
源码如下:
public class Collections {
private Collections() {
}
/**
* Returns an enumeration over the specified collection. This provides
* interoperability with legacy APIs that require an enumeration
* as input.
*
* @param <T> the class of the objects in the collection
* @param c the collection for which an enumeration is to be returned.
* @return an enumeration over the specified collection.
* @see Enumeration
*/
public static <T> Enumeration<T> enumeration(final Collection<T> c) {
return new Enumeration<T>() {
private final Iterator<T> i = c.iterator();
public boolean hasMoreElements() {
return i.hasNext();
}
public T nextElement() {
return i.next();
}
};
}
}
案例二
日志框架 slf4j 晚于一些主流日志框架,它定义了日志接口 org.slf4j.Logger,其中包含了日志记录的 api
public interface Logger {
public void info(String msg);
.
.
.
}
slf4j 为了能适配其他日志框架,提供了各种适配库。
比如为了适配 log4j,在 slf4j-log4j.jar 包中提供 org.slf4j.impl.Log4jLoggerAdapter 记录日志的适配类,Log4jLoggerAdapter 继承自 org.slf4j.spi.LocationAwareLogger 继承自 org.slf4j.Logger。
Log4jLoggerAdapter 持有了 org.apache.log4j.Logger 对象,完成了用该 log4j 的日志对象实现 slf4j 的日志接口中方法的适配。
public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable { //log4j 中的 Logger 对象 final transient org.apache.log4j.Logger logger; Log4jLoggerAdapter(org.apache.log4j.Logger logger) { this.logger = logger; this.name = logger.getName(); traceCapable = isTraceCapable(); } // slf4j 中的 api public void info(String msg) { logger.log(FQCN, Level.INFO, msg, null); } . . .}
↓↓ 查看脑图
更多相关文章
- 详解第三种创建线程的方式-Callable接口
- 【编测编学】接口测试面试题必背(下)
- java中的日志框架梳理(以故事的形式呈现)
- 快速测试 API 接口的新技能
- 生产环境下的 Node.js 日志记录方案[每日前端夜话0xFD]
- 「Jenkins」- 使用接口批量创建任务
- Java 抽象类与接口的区别