12 Oct 2014

Java设计模式:迭代器模式

注:本文为译文,原文出处java-design-patterns-in-stories

迭代器模式应用于遍历对象的集合. 它是一个很常用的模式, 或许你之前已经用过他了. 只要你见过像hasNext()next(), 它可能就是迭代器模式. 例如: 你可以遍历一个数据库查询记录的链表.

迭代器模式类图

iterator-design-pattern

迭代器模式Java代码

interface IIterator{
    public boolean hasNext();
    public Object next();
}

interface IContainer{
    public IIterator createIterator();
}

class RecordCollection implements IContainer{
    private String recordArray[] = {"first","second","third","fourth","fifth"};

    public IIterator createIterator(){
        RecordIterator iterator = new RecordIterator();
        return iterator;
    }

    private class RecordIterator implements IIterator{
        private int index;

        public boolean hasNext(){
            if (index < recordArray.length)
                return true;
            else
                return false;
        }

        public Object next(){
            if (this.hasNext())
                return recordArray[index++];
            else
                return null;
        }
    }
}

public class TestIterator {
    public static void main(String[] args) {
        RecordCollection recordCollection = new RecordCollection();
        IIterator iter = recordCollection.createIterator();

        while(iter.hasNext()){
            System.out.println(iter.next());
        }
    }
}

迭代器模式在JDK中的应用

java.util包内, Iterator接口定义如下:

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

还有可以创建迭代器的类, 例如: TreeSet#iterator(), HashSet#iterator()等.


Tags:
0 comments