天天看點

設計模式(十七) 疊代器模式

疊代器模式是現在使用非常廣泛的一種模式,Java、C#等很多語言都是用疊代器建立集合,然後提供

for-each

文法糖讓我們能夠友善的周遊集合。如果對Java或C#等語言的集合比較熟悉的話,那麼疊代器模式你也一定很熟悉。

首先我們來編寫疊代器的接口。該接口有兩個方法,next()和hasNext(),用于判斷是否存在下一個值并擷取目前值。

public interface Iterator {
    boolean hasNext();

    int next();
}
           

為了配套,一般情況下還有另外一個接口

Iterable

,集合類一般需要實作該接口表示可以從集合類上擷取疊代器。

public interface Iterable {
    Iterator getIterator();
}
           

然後我們來編寫一個自定義集合和該集合的疊代器。注意,疊代器的起始索引應該設定為第一個元素的前一個,這樣才能讓第一次調用next()擷取第一個元素。

public class MyCollection implements Iterable {
    private int[] array;

    public MyCollection(int[] array) {
        this.array = array;
    }

    @Override
    public Iterator getIterator() {
        return new MyCollectionIterator(array);
    }
}

class MyCollectionIterator implements Iterator {
    private int[] array;
    private int current;

    public MyCollectionIterator(int[] array) {
        this.array = array;
        current = -1;
    }

    @Override
    public boolean hasNext() {
        return current <= array.length - 2;
    }

    @Override
    public int next() {
        return array[++current];
    }
}
           

最後我們來看看運作結果。不出意外的話整個集合都會正确周遊。

public void run() {
        int[] array = {1, 2, 3, 4, 5, 6};
        MyCollection myCollection = new MyCollection(array);

        Iterator iterator = myCollection.getIterator();
        while (iterator.hasNext()) {
            System.out.printf("%d ", iterator.next());
        }
        System.out.println();
    }
           

讓我們最後再回想一下疊代器使用的現成例子:Java的集合類大多數都實作了疊代器模式;JDBC的結果集也實作了疊代器模式;舊的Java的

Enumeration

也是一個實作了疊代器的例子。還有很多,這裡就不一一列舉了。