Collections.unmodifiableList方法

 在讀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);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章