编辑
2025-09-28
C#
00

目录

摘要
正文
迭代器模式的结构
迭代器模式的应用场景
集合类遍历
文件系统遍历
数据库查询结果遍历
例子
总结

摘要

迭代器模式是一种行为型设计模式,它提供了一种访问和遍历容器对象中各个元素的方法,而不需要暴露容器的内部结构。通过使用迭代器模式,可以将遍历算法与容器对象分离,使得容器对象的结构和遍历行为可以独立地变化。

正文

迭代器模式的结构

迭代器模式包含以下几个角色:

  • 迭代器(Iterator):定义访问和遍历元素的接口。
  • 具体迭代器(Concrete Iterator):实现迭代器接口,负责实现具体的遍历算法。
  • 容器(Container):定义获取迭代器的方法。
  • 具体容器(Concrete Container):实现容器接口,负责创建具体迭代器对象。

迭代器模式的应用场景

迭代器模式适用于以下情况:

  • 当需要遍历一个容器对象的元素时,可以使用迭代器模式。
  • 当需要对容器对象的遍历算法进行封装时,可以使用迭代器模式。
  • 当需要提供多种遍历方式时,可以使用迭代器模式。

以下是一些可能的应用场景:

集合类遍历

在一个集合类中,可以使用迭代器模式来遍历集合中的元素。例如,可以使用迭代器模式来遍历一个数组、列表或字典中的元素。

文件系统遍历

在一个文件系统中,可以使用迭代器模式来遍历文件和文件夹。例如,可以使用迭代器模式来遍历一个文件夹中的所有文件和子文件夹。

数据库查询结果遍历

在一个数据库查询中,可以使用迭代器模式来遍历查询结果。例如,可以使用迭代器模式来遍历一个查询结果集中的所有记录。

例子

我们需要定义一个迭代器接口IIterator,其中包含访问和遍历元素的方法:

C#
public interface IIterator { bool HasNext(); object Next(); }

我们有一个名为Aggregate的容器接口,其中包含获取迭代器的方法GetIterator()

C#
public interface IAggregate { IIterator GetIterator(); }

我们可以创建一个具体容器类ConcreteAggregate,实现IAggregate接口,并在GetIterator()方法中返回一个具体迭代器对象:

C#
public class ConcreteAggregate : IAggregate { private List<object> _items = new List<object>(); public void AddItem(object item) { _items.Add(item); } public IIterator GetIterator() { return new ConcreteIterator(this); } public int Count { get { return _items.Count; } } public object this[int index] { get { return _items[index]; } set { _items[index] = value; } } }

然后,我们可以创建一个具体迭代器类ConcreteIterator,实现IIterator接口,并在HasNext()Next()方法中实现具体的遍历逻辑:

C#
public class ConcreteIterator : IIterator { private ConcreteAggregate _aggregate; private int _index; public ConcreteIterator(ConcreteAggregate aggregate) { _aggregate = aggregate; _index = 0; } public bool HasNext() { return _index < _aggregate.Count; } public object Next() { object item = _aggregate[_index]; _index++; return item; }

现在,我们可以在客户端代码中使用迭代器模式来遍历容器中的元素:

C#
static void Main(string[] args) { var aggregate = new ConcreteAggregate(); aggregate.AddItem("Item 1"); aggregate.AddItem("Item 2"); aggregate.AddItem("Item 3"); var iterator = aggregate.GetIterator(); while (iterator.HasNext()) { object item = iterator.Next(); Console.WriteLine(item); } }

image.png

总结

迭代器模式是一种将遍历算法与容器对象分离的设计模式,它提供了一种访问和遍历容器对象中各个元素的方法。通过使用迭代器模式,可以实现更灵活、可扩展和可维护的代码。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!