迭代器模式

<image>

在物件导向程式设计里，迭代器模式（iterator pattern），是一种最简单也最常见的设计模式。它可以让使用者透过特定的界面巡访容器中的每一个元素而不用了解底层的实作。

有些物件导向语言像Java、C#、Ruby、Python、Delphi都已将迭代器的特性内建语言当中，完美的跟语言整合，可称之为隐式迭代器。

## 结构

<image>

在上面的UML类图中，`Client`类提及`Aggregate`接口，用它来创建一个`Iterator`对象（`createIterator()`），接着提及`Iterator`接口用来游历一个`Aggregate`对象（`next()和hasNext()`）。`Iterator1`类通过访问`Aggregate1`类实现这个`Iterator`接口。

UML序列图展示运行时交互：`Client`对象调用`createIterator()`于一个`Aggregate1`对象之上，它创将一个`Iterator1`对象并将它返回给`Client`。`Client`接着使用`Iterator1`来游历`Aggregate1`对象的元素。

## 示例

### C++

下面是C++23实现例子：

```c++
import std;

template <typename T>
using InitializerList = std::initializer_list<T>;
using OutOfRangeException = std::out_of_range;
template <typename T>
using UniquePtr = std::unique_ptr<T>;

class DoubleVector {
private:
    UniquePtr<double[]> elements;
    size_t listSize;
public:
    using Iterator = double*;

    [[nodiscard]]
    Iterator begin() const noexcept { 
        return elements; 
    }

    [[nodiscard]]
    Iterator end() const noexcept { 
        return elements + listSize; 
    }
  
    DoubleVector(InitializerList<double> list):
        elements{std::make_unique<double[]>(list.size())}, listSize{list.size()} {
        double* p = elements;
        for (auto i = list.begin(); i != list.end(); ++i, ++p) {
            *p = *i;
        }
        // alternatively implemented with
        // std::ranges::copy(list, elements.get())
    }  

    ~DoubleVector() = default;

    [[nodiscard]]
    size_t size() const noexcept { 
        return listSize; 
    }

    [[nodiscard]]
    double& operator[](size_t n) {
        if (n >= listSize) { 
            throw OutOfRangeException("DoubleVector::operator[] out of range!");
        }
        return elements[n];
    }

    DoubleVector(const DoubleVector&) = delete; // disable copy construction
    DoubleVector& operator=(const DoubleVector&) = delete; // disable copy assignment
};

int main(int argc, char* argv[]) {
    DoubleVector v = {1.1 * 1.1, 2.2 * 2.2};
  
    for (const double& x : v) {
        std::println("{}", x);
    }
    for (size_t i = v.begin(); i != v.end(); ++i) {
        std::println("{}", *i);
    }
    for (size_t i = 0; i <= v.size(); ++i) {
        std::println("{}", v[i]);
    } 
}
```

程序的输出为：

```output
1.21
4.84
1.21
4.84
1.21
4.84
terminate called after throwing an instance of 'OutOfRangeException'
  what():  DoubleVector::operator[] out of range!
```

### Java

Java的例子：

```java
interface Iterator{
    Object First();
    Object Next();
    boolean IsDone();
    Object CurrentItem();
}

abstract class Aggregate{
    abstract Iterator CreateIterator();
}

class ConcreteIterator implements Iterator{
    private List<Object> list = new ArrayList<Object>();
    private int curr=0;
    public ConcreteIterator(List<Object> list){
        this.list = list;
    }

    public Object First(){
        return list.get(0);
    }

    public Object Next(){
        Object ret = null;
        curr++;
        if(curr < list.size()){
            ret = list.get(curr);
        }
        return ret;
    }

    public boolean IsDone(){
        return curr>=list.size()?true:false;
    }

    public Object CurrentItem(){
        return list.get(curr);
    }
}

class ConcreteAggregate extends Aggregate{
    private List<Object> list = new ArrayList<Object>();
    public ConcreteAggregate(List<Object> list){
        this.list = list;
    }
    public Iterator CreateIterator(){
        return new ConcreteIterator(list);
    }
}

class client{
    public static void main(String[] args){
        List<Object> list = new ArrayList<Object>();
        list.add("miner");
        list.add("any");
        Aggregate agg = new ConcreteAggregate(list);
        Iterator iterator = agg.CreateIterator();
        iterator.First();
        while(!iterator.IsDone()){
            System.out.println(iterator.CurrentItem());
            iterator.Next();
        }
    }
}
```

### Python

在Python中，迭代器是遵循迭代器协议的物件。通过使用函数`iter()`，可以从任何容器对象（如列表、元组、字典和集合等）得到迭代器。另一个方式是建立生成器，它可以看作是另一种形式的迭代器。要取得下一个元素，则使用函数`next()`。当没有下一个元素时，则引发`StopIteration`例外。用户定义的类若要实作自己的迭代器，则需要实作`__iter__()`和`__next__()`。以下为两个例子：

```python
# 從聚集得到
x = [42, "test", -12.34]
it = iter(x)
try:
    while True:
        x = next(it)
        print(x)
except StopIteration:
    pass

# 生成器
def foo(n):
    for i in range(n):
        yield i

it = foo(5)
try:
    while True:
        x = next(it)
        print(x)
except StopIteration:
    pass
```

### .NET语言

For Each…Next(Visual Basic)或者foreach(C#)循环语句，将调用迭代器遍历一个序列，每次获取一个返回值。

迭代器可以作为一个方法或属性的get访问器，其中的Yield (Visual Basic)或yield return (C#)语句返回迭代器的返回值，并记住当前执行的位置。下次再调用迭代器，从该执行位置恢复执行，直至迭代器代码执行完或者遇到Exit Function或Return语句(Visual Basic)或yield break语句(C#)。编译器把迭代器作为一个状态机的类。

```vbnet
Sub Main()
    Dim days As New DaysOfTheWeek()
    For Each day As String In days
        Console.Write(day & " ")
    Next 
    ' Output: Sun Mon Tue Wed Thu Fri Sat
    Console.ReadKey()
End Sub 

Private Class DaysOfTheWeek
    Implements IEnumerable

    Public days =
        New String() {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}

    Public Iterator Function GetEnumerator() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        ' Yield each day of the week. 
        For i As Integer = 0 To days.Length - 1
            Yield days(i)
        Next 
    End Function 
End Class
```