在读mybatis源码时,发现其拦截器链是这么写的:
package org.apache.ibatis.plugin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Clinton Begin
*/
public class InterceptorChain {
//final标识interceptors 引用不可变
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
//可以添加拦截器
public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
}
//返回一个不可修改(准确的说,上边有个addInterceptor()方法可以添加,但是不可删除)的列表
public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
Collections.unmodifiableList方法平时用的不多,如果有类似的场景需求:持有一个不可变的集合,不仅指向该集合的引用不可变,集合内的元素也不可变,参考以上的代码,把add方法去掉以后,就可以做到彻底不可变。可以参考如下:
/**
* <p>Title: Test</p>
* <p>Description: </p>
* @author wangzhj
* @date 2020年1月11日
*/
public class Test {
private static final List<String> interceptors = new ArrayList<String>();
static{
interceptors.add("1");
interceptors.add("2");
}
public static List<String> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
/**
* <p>Title: main</p>
* <p>Description: </p>
* @param args
*/
public static void main(String[] args) {
//抛出异常lang.UnsupportedOperationException
// Test.getInterceptors().add("c");
Test.getInterceptors().forEach(System.out::println);
}
}