設計模式-行爲型之迭代器(Iterator)模式

定義

  • 一個一個的遍歷,將遍歷與實現分離開來。

使用場景

  • 集合中元素的遍歷。
  • 可以定製化遍歷方式。

UML圖

在這裏插入圖片描述

代碼實現

public class Aggregate {

    private int[] elements;
    //元素個數
    private int last;

    //size :數組大小
    public Aggregate(int size) {
        this.elements = new int[size];
    }
    //獲取元素個數
    public int getLength(){
        return last;
    }

    public void addElement(int value){
        elements[last] = value;
        last++;
    }

    public int getElement(int index){
        return elements[index];
    }

    // 獲取遍歷器
    public Iterator getIterator(){
        return new ConcreteIterator(this);
    }

}
//迭代器接口
public interface Iterator<T> {

    // 判斷是否還有元素
    public boolean hasNext();

    // 返回當前元素
    public T next();
}
// 具體的迭代器
public class ConcreteIterator implements Iterator {

    private Aggregate aggregate;

    private int index;

    public ConcreteIterator(Aggregate aggregate) {
        this.aggregate = aggregate;
        this.index = 0;
    }

    @Override
    public boolean hasNext() {
        return index < aggregate.getLength();
    }

    @Override
    public Object next() {
        int element = aggregate.getElement(index);
        index++;
        return element;
    }
}
// 測試
public class Client {
    public static void main(String[] args) {
        Aggregate aggregate = new Aggregate(10);
        for (int i=10;i>0;i--){
            aggregate.addElement(i);
        }
        Iterator iterator = aggregate.getIterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

總結

  • 將遍歷與實現分離開來。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章