设计模式课程 设计模式精讲 18-3 迭代器模式源码解析

1    源码解析

1.1    源码解析1(jdk中的应用)

1.2    源码解析2(mybaties中的应用)

 

1    源码解析
1.1    源码解析1(jdk中的应用)

java.util.Iterator(接口)

public interface Iterator<E> {
    /**
     * Returns {@code true} if the iteration has more elements.
     * (In other words, returns {@code true} if {@link #next} would
     * return an element rather than throwing an exception.)
     *
     * @return {@code true} if the iteration has more elements
     */
  //和我们18-2中的isNext有相同的作用
boolean hasNext();
}

java.util.ArrayList(实现)

private class Itr implements Iterator<E> {

        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];
        }


}
1.2    源码解析2(mybaties中的应用)

DefaultCursor.java

public class DefaultCursor<T> implements Cursor<T> {
//创建了游标迭代器 
private final CursorIterator cursorIterator = new CursorIterator();
@Override
public Iterator<T> iterator() { if (iteratorRetrieved) { throw new IllegalStateException("Cannot open more than one iterator on a Cursor"); } iteratorRetrieved = true; return cursorIterator; } }

 

猜你喜欢

转载自www.cnblogs.com/1446358788-qq/p/11602443.html