【十四】Java设计模式GOF23之迭代器模式

版权声明:转载注明出处 https://blog.csdn.net/jy02268879/article/details/86527530

简介

迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。

它提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。

迭代器模式的结构

1.抽象容器:一般是一个接口,提供一个iterator()方法,例如java中的Collection接口,List接口,Set接口等。
2.具体容器:就是抽象容器的具体实现类,比如List接口的有序列表实现ArrayList,List接口的链表实现LinkList,Set接口的哈希列表的实现HashSet等。
3.抽象迭代器:定义遍历元素所需要的方法,一般来说会有这么三个方法:取得第一个元素的方法first(),取得下一个元素的方法next(),判断是否遍历结束的方法isDone()(或者叫hasNext()),移出当前对象的方法remove(),
4.迭代器实现:实现迭代器接口中定义的方法,完成集合的迭代。

例子

例子是JDK源码的ArrayList中的

UML图

1.抽象容器:List

2.具体容器:ArrayList

3.抽象迭代器:Iterator

4.迭代器实现:Itr。它是ArrayList中的一个内部类。

代码

 抽象容器List接口

public interface List<E> extends Collection<E> {
    Iterator<E> iterator();
    //与迭代器模式举例无关的代码不贴
}

具体容器ArrayList

public class ArrayList<E> implements List<E>{
    transient Object[] elementData; 
    public Iterator<E> iterator() {
        return new Itr();
    }
    //与迭代器模式举例无关的代码不贴
}

抽象迭代器接口Iterator

package java.util;

import java.util.function.Consumer;


public interface Iterator<E> {
 
    boolean hasNext();

    E next();


    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

迭代器实现Itr,其中elementData是ArrayList中的。实际上Itr类是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;

        Itr() {}

        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();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

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

猜你喜欢

转载自blog.csdn.net/jy02268879/article/details/86527530
今日推荐