重温设计模式 --- 迭代器模式

引言

迭代器模式是一种行为型设计模式,它允许按照特定顺序遍历集合对象的元素,同时不暴露集合的内部结构。这样做可以让客户端代码不依赖于集合对象的具体实现,从而提高代码的灵活性和可重用性。

在迭代器模式中,聚合对象将其遍历的职责委托给迭代器对象,而不是在聚合对象中实现遍历。

迭代器模式的优点是可以支持以不同的方式遍历一个聚合对象,而且可以隐藏遍历元素的内部细节。

在 C# 中,迭代器模式可以通过实现IEnumerableIEnumerator接口来实现。其中 IEnumerable接口定义了一个GetEnumerator方法,返回一个实现了IEnumerator接口的迭代器对象。IEnumerator接口则定义了访问集合中元素的方法,包括CurrentMoveNextReset等。

迭代器实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class MyCollection : IEnumerable
{
private int[] items = new int[5] { 31, 12, 3, 64, 51 };

// 实现 IEnumerable 接口,返回一个枚举器
public IEnumerator GetEnumerator()
{
return new MyEnumerator(items);
}

// 自定义迭代器类
private class MyEnumerator : IEnumerator
{
private int[] items;
private int position = -1;

public MyEnumerator(int[] items)
{
this.items = items;
}

public object Current
{
get
{
if (position >= 0 && position < items.Length)
{
return items[position];
}
else
{
throw new InvalidOperationException();
}
}
}

public bool MoveNext()
{
position++;
return (position < items.Length);
}

public void Reset()
{
position = -1;
}
}
}

这样我们可以直接使用foreach进行遍历:

1
2
3
4
5
6
new MyCollection();

foreach (int item in collection)
{
Console.WriteLine(item);
}

输出结果

1
2
3
4
5
31
12
3
64
51

结论

这就是迭代器模式的基本用法。它可以让我们轻松地遍历集合对象中的元素,而不必暴露集合的内部结构。此外,通过实现IEnumerableIEnumerator接口,我们可以轻松地在 C# 中实现迭代器模式。

:::tip{title=”提示”}
foreach是c#语法糖,用来遍历实现了IEnumerable接口的集合类。

foreach 循环的原理是通过调用集合类的GetEnumerator方法,返回一个实现了IEnumerator接口的迭代器对象,然后通过迭代器对象的MoveNext方法,依次访问集合中的每个元素,直到集合中的所有元素都被访问完毕。
:::