从Spring源码理解适配器模式
这个类从方法命名上看是一个适配器,我们先看代码:
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof MethodBeforeAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
return new MethodBeforeAdviceInterceptor(advice);
}
}
这里我们找到适配的接口了,那我们的被适配类呢?
注意这里的getInterceptor()方法,返回的是个对象–>MethodBeforeAdviceInterceptor,那么他算不算被适配对象?
接着继续看这个类:
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {
private final MethodBeforeAdvice advice;
/**
* Create a new MethodBeforeAdviceInterceptor for the given advice.
* @param advice the MethodBeforeAdvice to wrap
*/
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
Assert.notNull(advice, "Advice must not be null");
this.advice = advice;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
return mi.proceed();
}
}
这里看这个拦截器,看内容,其实是个标准的适配器模式的实现,通过接口适配MethodBeforeAdvice 对象,对外适配提供invoke方法。
好了,这两个类连在一起看有啥感觉?
总结
1.MethodBeforeAdviceAdapter通过预定接口getInterceptor(Advisor advisor)适配MethodBeforeAdviceInterceptor对象,为啥?因为被适配对象MethodBeforeAdviceInterceptor没有getInterceptor(Advisor advisor),我在我的方法里调用你去实现,就算是适配。
2.MethodBeforeAdviceInterceptor又通过invoke(MethodInvocation mi)方法继续进行适配,被适配的对象是MethodBeforeAdvice
3.怎么说呢,看起来很像普通的接口实现,但是因为持有了其他对象,相当于只是包装了下其他对象,对外提供**(想要的目标方法)这个是重中之重**