从Spring源码理解适配器模式

从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.怎么说呢,看起来很像普通的接口实现,但是因为持有了其他对象,相当于只是包装了下其他对象,对外提供**(想要的目标方法)这个是重中之重**

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值