1. 程式人生 > 其它 >Java-迭代器-設計模式(十五)

Java-迭代器-設計模式(十五)

技術標籤:設計模式Java基礎java設計模式

說明

迭代器模式(Iterator),提供一種方法順序訪問一個聚合物件中的各種元素,而又不暴露該物件的內部表示。

角色:
1.Iterator(迭代器)
迭代器定義訪問和遍歷元素的介面
2.ConcreteIterator (具體迭代器)
具體迭代器實現迭代器介面,對該聚合遍歷時跟蹤當前位置
3.Aggregate (聚合)
聚合定義建立相應迭代器物件的介面
4.ConcreteAggregate (具體聚合)
具體聚合實現建立相應迭代器的介面,該操作返回ConcreteIterator的一個適當的例項

程式碼

自定義一個字串集合的迭代器,程式碼如下。

迭代器角色,定義訪問和遍歷元素的介面

/**
 * @author ctl
 * @date 2021/1/26
 */
public interface Iterator {

    // 獲取前一個
    public Object prev();

    // 獲取後一個
    public Object next();

    // 是否還可以繼續迭代
    public boolean hasNext();

    // 指標置為起始位置並返回對應值
    public Object first();
}

具體迭代器角色,實現迭代器介面,對該聚合遍歷時跟蹤當前位置

/**
 * @author ctl
 * @date 2021/1/26
 */
public class ConcreteIterator implements Iterator { private Collection collection; private int pos = -1; public ConcreteIterator(Collection collection) { this.collection = collection; } @Override public Object prev() { if (pos > 0) { pos--; }
return collection.get(pos); } @Override public Object next() { if (pos < collection.size() - 1) { pos++; } return collection.get(pos); } @Override public boolean hasNext() { return pos < collection.size() - 1; } @Override public Object first() { pos = 0; return collection.get(pos); } }

聚合角色,定義建立相應迭代器物件的介面

/**
 * @author ctl
 * @date 2021/1/26
 */
public interface Collection {

    public Iterator iterator();

    public Object get(int i);

    public int size();
}

具體聚合角色,實現建立相應迭代器的介面,該操作返回ConcreteIterator的一個適當的例項

/**
 * @author ctl
 * @date 2021/1/26
 */
public class ConcreteCollection implements Collection {

    private String[] strs;

    public ConcreteCollection(String[] strs) {
        this.strs = strs;
    }

    @Override
    public Iterator iterator() {
        return new ConcreteIterator(this);
    }

    @Override
    public Object get(int i) {
        return strs[i];
    }

    @Override
    public int size() {
        return strs.length;
    }
}

測試類

/**
 * @author ctl
 * @date 2021/1/26
 */
public class IteratorMain {
    public static void main(String[] args) {
        String[] strs = {"a", "b", "c", "d", "e"};
        Collection collection = new ConcreteCollection(strs);
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }
    }
}

結果
結果
完成了對字串的迭代。

總結

其實我們對迭代器並不陌生,jdk中的很多集合類都實現了迭代器模式,我們可以根據迭代器模式的思想實現個性化的迭代器,從而達到使用不同的方式來對集合進行遍歷。
比如本例中實現了一個first方法,可以在任意過程中將指標指向首位然後再繼續迭代,當然也可以實現將指標指向隨意一個有效位置進行迭代,或者實現反向迭代等等。