设计模式 16 迭代器模式

设计模式 16

  • 创建型模式(5):工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式
  • 结构型模式(7):适配器模式、桥接模式、组合模式、装饰者模式、外观模式、享元模式、代理模式
  • 行为型模式(11):责任链模式、命令模式、解释器模式、迭代器模式、中介者模式、备忘录模式、观察者模式、状态模式、策略模式、模板方法模式、访问者模式

迭代器模式(Iterator Pattern)

1 定义

迭代器模式的核心思想是提供一种统一的接口来遍历聚合对象中的元素,而不需要了解聚合对象的内部结构。通过这种方式,集合和遍历算法之间解耦,遍历的方式可以更容易地改变或扩展。

2 结构

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

  • 迭代器接口(Iterator): 定义访问和遍历元素的接口,通常包括 NextHasNextCurrent 等方法。
  • 具体迭代器(ConcreteIterator): 实现迭代器接口,负责具体元素的遍历。
  • 聚合接口(Aggregate): 定义创建迭代器对象的接口。
  • 具体聚合类(ConcreteAggregate): 实现聚合接口,返回具体的迭代器实例。

UML 类图

+-------------------------------+       +-------------------+
|   Aggregate                   |       |     Iterator      |
+-------------------------------+       +-------------------+
| + CreateIterator(): Iterator  |       | + HasNext(): bool |
+-------------------------------+       | + Next(): T       |
        ^                               | + Current(): T    |
        |                               +-------------------+
+-------------------------------+
|ConcreteAggregate              |       +-------------------+
+-------------------------------+       | ConcreteIterator  |
| + CreateIterator(): Iterator  |       | + HasNext(): bool |
+-------------------------------+       | + Next(): T       |
                                        | + Current(): T    |
                                        +-------------------+

3 示例代码

假设我们要实现一个自定义的 List 集合,并为它提供一个迭代器来遍历其中的元素。

迭代器接口

// 迭代器接口
public interface IIterator<T>
{
    bool HasNext();
    T Next();
    T Current { get; }
}

具体迭代器

// 具体迭代器
public class ListIterator<T> : IIterator<T>
{
    private readonly List<T> _list;
    private int _position = 0;

    public ListIterator(List<T> list)
    {
        _list = list;
    }

    public bool HasNext()
    {
        return _position < _list.Count;
    }

    public T Next()
    {
        return _list[_position++];
    }

    public T Current => _list[_position];
}

聚合接口

// 聚合接口
public interface IAggregate<T>
{
    IIterator<T> CreateIterator();
}

具体聚合类

// 具体聚合类
public class CustomList<T> : IAggregate<T>
{
    private readonly List<T> _items = new List<T>();

    public void Add(T item)
    {
        _items.Add(item);
    }

    public IIterator<T> CreateIterator()
    {
        return new ListIterator<T>(_items);
    }
}

客户端代码

class Program
{
    static void Main(string[] args)
    {
        // 创建聚合对象并添加元素
        CustomList<string> list = new CustomList<string>();
        list.Add("Item 1");
        list.Add("Item 2");
        list.Add("Item 3");

        // 创建迭代器并遍历元素
        IIterator<string> iterator = list.CreateIterator();
        while (iterator.HasNext())
        {
            string item = iterator.Next();
            Console.WriteLine(item);
        }
    }
}

运行结果

Item 1
Item 2
Item 3

在这个例子中,我们创建了一个自定义的 CustomList 类,并为其提供了 ListIterator 作为具体的迭代器。ListIterator 实现了遍历列表元素的逻辑。客户端代码通过迭代器接口来遍历 CustomList 中的元素,而无需了解 CustomList 的内部结构。

6 特点

  • 优点:

    • 简化聚合类: 迭代器模式将遍历的职责从聚合类中分离出来,简化了聚合类的实现。

    • 一致的接口: 迭代器模式提供了一致的接口用于遍历不同类型的聚合对象,无需关心其内部实现。

    • 灵活性高: 可以自由更改迭代算法而不影响聚合类。

  • 缺点:

    • 开销增加: 对于非常简单的聚合类,引入迭代器模式可能会导致额外的开销和复杂性。

7 适用场景

  • 需要遍历聚合对象: 当需要遍历一个聚合对象中的元素时,可以使用迭代器模式。
  • 不同的遍历方式: 需要多种遍历方式或需要隐藏遍历的实现细节时,迭代器模式是一个合适的选择。
  • 统一的遍历接口: 当需要为不同类型的聚合对象提供统一的遍历接口时,迭代器模式非常适用。

8 总结

迭代器模式提供了一种遍历聚合对象的标准方法,通过解耦遍历逻辑和聚合对象的实现,增强了系统的灵活性和可扩展性。该模式特别适合需要在不暴露对象内部结构的情况下对对象进行遍历的场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WineMonk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值