适配器模式在开源代码中的应用

适配器模式的作用:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。

开源代码中,哪些地方用到了适配器模式呢?

案例一

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 的日志接口中方法的适配。

扫描二维码关注公众号,回复: 11644681 查看本文章
public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable {
	final transient org.apache.log4j.Logger logger;
	
	Log4jLoggerAdapter(org.apache.log4j.Logger logger) {
        this.logger = logger;
        this.name = logger.getName();
        traceCapable = isTraceCapable();
    }
	
	public void info(String msg) {
        logger.log(FQCN, Level.INFO, msg, null);
    }
	.
	.
	.
}

【Java学习资源】整理推荐


【Java面试题与答案】整理推荐

猜你喜欢

转载自blog.csdn.net/meism5/article/details/107601789