模式简介
迭代器模式是一种行为型设计模式,它为集合对象提供了简便的遍历接口,隐藏了具体的遍历逻辑,除此之外它能够为任何可以获取统一迭代器的集合提供一致的遍历方法,增加了代码的复用性,这对于调用者而言,可以采用同样的方式遍历不同类型的集合,简化了调用逻辑。
常见的应用场景:遍历集合对象、封装不同数据结构的遍历、数据库查询结果集、文件系统遍历、菜单导航、文档解析、线程池管理。
模式结构
-
迭代器接口(Iterator): 定义了遍历元素的接口,包括
next()
方法用于获取下一个元素,以及hasNext()
方法用于检查是否还有更多元素。 -
具体迭代器(Concrete Iterator): 实现迭代器接口,负责实际遍历集合并跟踪当前位置。
-
聚合接口(Aggregate): 定义了创建迭代器的接口,通常包括一个或多个方法返回相应的迭代器。
-
具体聚合对象(Concrete Aggregate): 实现聚合接口,返回适当的具体迭代器。
工作原理
-
客户端(Client): 客户端通过聚合接口获取迭代器对象,然后使用迭代器对象遍历集合中的元素。
-
聚合对象(Aggregate): 聚合对象负责创建迭代器,并通过其接口返回具体的迭代器对象。
-
迭代器接口和具体迭代器(Iterator和Concrete Iterator): 迭代器接口定义了遍历元素的方法,具体迭代器实现了这些方法,负责实际的遍历逻辑和状态管理。迭代器通过追踪当前位置来确保逐个访问集合元素。
-
具体聚合对象(Concrete Aggregate): 具体聚合对象实现聚合接口,其中的方法返回相应的具体迭代器对象。这个具体聚合对象可以是实际的集合,如列表或数组。
代码示例(C#)
提示:可在本栏目的资源篇“设计模式代码示例合集”下载所有完整代码资源。
迭代器:Iterator.cs
namespace IteratorPattern;
// 迭代器接口
interface IIterator
{
// 是否存在下一个元素
bool HasNext();
// 下一个元素
object next { get; }
}
// 可迭代接口
interface Iterable
{
// 获取迭代器
IIterator GetIterator();
}
集合:Collection.cs
namespace IteratorPattern;
// 集合元素
struct CollectionItem
{
public int value; // 集合元素的值
public CollectionItem(int value)
{
this.value = value;
}
public override string ToString()
{
return "value:" + value;
}
}
// 集合迭代器
class CollectionIterator : IIterator
{
public object next
{
get
{
try
{
return collectionItems[index++];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
private CollectionItem[] collectionItems; // 集合元素合集
private int index; // 当前所访问元素的索引
public CollectionIterator(CollectionItem[] collectionItems)
{
this.collectionItems = collectionItems;
index = 0;
}
public bool HasNext()
{
return index < collectionItems.Length;
}
}
// 集合
class Collection : Iterable
{
private CollectionItem[] collectionItems; // 集合元素合集
public Collection(CollectionItem[] collectionItems)
{
if (collectionItems == null || collectionItems.Length == 0)
{
this.collectionItems = Array.Empty<CollectionItem>();
}
else
{
this.collectionItems = new CollectionItem[collectionItems.Length];
Array.Copy(collectionItems, this.collectionItems, collectionItems.Length);
}
}
public IIterator GetIterator()
{
return new CollectionIterator(collectionItems);
}
}
测试代码:Program.cs
// ************* 14.迭代器模式测试 **************
using IteratorPattern;
// 定义集合元素合集并传递给集合实例,通过集合实例获取迭代器
CollectionItem[] collectionItems = { new CollectionItem(1), new CollectionItem(2), new CollectionItem(3) };
Collection collection = new Collection(collectionItems);
IIterator iterator = collection.GetIterator();
// 通过迭代器遍历集合
while (iterator.HasNext())
{
Console.WriteLine(iterator.next);
}
代码解说
上述代码演示了对实现了Iterable接口的集合通过迭代器进行遍历。集合实现Iterable接口,提供获取迭代器的方法,集合迭代器实现了IIterator接口,提供了统一的遍历方法。调用者通过集合获取集合迭代器,再通过集合迭代器遍历集合中的元素。
如果这篇文章对你有帮助,请给作者点个赞吧!