Java的集合框架以其成功易用的设计征服了很多人(包括我),并且教科书式的诠释了泛型的应用方式。
我也是被 Joshua Bloch 的书引领入门,从中得益良多。我当然不会认为自己在设计上比他懂得更多,我也不知道当初Collection框架设计时为什么没有提供一个“只读”层面的接口,或许站在他的高度,有许多我所不知道的考量吧。
不过我在实际工作中不止一次遇到了这种需要“只读的列表”接口的情况,我不要 UnsupportedOperationException,我要更纯粹的——干脆没有提供任何modify方法的接口,于是有了下面这个 ListView,拿来与同样需要的人分享:
/* * Copyright 2013 (raistlic@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This interface does not extends {@link java.util.Collection}, because java's * collection interface is essentially a "mutable collection" interface, while * this interface tries to define a read-only list view. * * <p/> * Design ideas from {@link java.util.List}. * * @author raistlic */ public interface ListView<E> extends Iterable<E> { public int size(); public E get(int index); public int indexOf(E element); public boolean isEmpty(); public boolean contains(E element); }
在实际应用中,我遇到的情况是需要(跨线程)安全的发布一个ListView,然后任何线程可以安全对这个list view进行size查询、迭代访问等操作,而不必担心它会改变,这个 ListView 实现本身是 immutable 的,并且它背后的提供者用一种 “copy on write” 的方式来维护其内部的 reference。