`

迭代器模式

阅读更多

和原型模式一样,迭代器模式也基本不需要自己实现了,Java中提供了Iterator接口,可直接实现迭代器。迭代器模式也非常简单,就是为不同的集合统一遍历接口。
这里看下Java中迭代器的实现代码,以ArrayList为例

//ArrayList实现了List接口
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

//List继承了Collection
public interface List<E> extends Collection<E>

//Collection继承了Iterable接口
public interface Collection<E> extends Iterable<E>

//Iterable只有一个方法,就是返回Iterator对象,Iterator对象的作用就是对List的遍历
 public interface Iterable<T> {
    Iterator<T> iterator();
}

//ArrayList里面实现了此iterator()方法,如下
 public Iterator<E> iterator() {
        return new Itr();
    }

//而Itr是ArrayList的内部类,且这个内部类实现了Iterator接口,实现对ArrayList遍历的具体方法
 private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

 

所以整体结构是这样的。集合类实现了Iterable接口,返回一个Iterator对象,这个对象针对此集合类实现遍历方法。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics