设计模式学习笔记之迭代器模式

来源:互联网 发布:如何查看java源码 编辑:程序博客网 时间:2024/04/30 01:52

定义:迭代器模式提供一种方法顺序访问一个聚合对象的各个元素,而又不暴露其内部的表示。

要点
迭代器允许访问聚合的元素,而不需要暴露它的内部结构。
迭代器将遍历工作封装进一个对象中。
当使用迭代器的时候,我们依赖聚合提供遍历。
迭代器提供了一个通用的接口,让我们遍历聚合项,当我们编码使用聚合项时,就可以使用多态机制。
jdk中迭代器的实现

public interface Iterator<E> {    
    boolean hasNext();    
    E next();    
    void remove();    
}  

public interface Iterable<T> {    
    Iterator<T> iterator();    

下面是AbstractList对Iterable实现

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { // List接口实现了Collection<E>, Iterable<E>   
    
    protected AbstractList() {    
    }          
    ...  //其它代码省略    
    public Iterator<E> iterator() {    
    return new Itr();  // 这里返回一个迭代器  
    }    
    
    private class Itr implements Iterator<E> {  // 内部类Itr实现迭代器  
         
    int cursor = 0;    
    int lastRet = -1;    
    int expectedModCount = modCount;    
    
    public boolean hasNext() {  // 实现hasNext方法  
            return cursor != size();    
    }    
    
    public E next() {  // 实现next方法  
            checkForComodification();    
        try {    
        E next = get(cursor);    
        lastRet = cursor++;    
        return next;    
        } catch (IndexOutOfBoundsException e) {    
        checkForComodification();    
        throw new NoSuchElementException();    
        }    
    }    
    
    public void remove() {  // 实现remove方法  
        if (lastRet == -1)    
        throw new IllegalStateException();    
    
        try {    
        AbstractList.this.remove(lastRet);    
        if (lastRet < cursor)    
            cursor--;    
        lastRet = -1;    
        expectedModCount = modCount;    
        } catch (IndexOutOfBoundsException e) {    
        throw new ConcurrentModificationException();    
        }    
    }    
    
    final void checkForComodification() {    
        if (modCount != expectedModCount)    
       throw new ConcurrentModificationException();    
    }    
    }    
}    

0 0
原创粉丝点击