IteratorPattern-迭代器模式

ZHIZRL / 2023-08-23 / 原文

在C#中,迭代器模式(Iterator Pattern)是一种行为型设计模式,它提供了一种方法来顺序访问一个聚合对象中的各个元素,而无需暴露聚合对象的内部表示。

迭代器模式有以下几个关键角色:

Iterator(迭代器):定义访问和遍历元素的接口。

ConcreteIterator(具体迭代器):实现迭代器接口,实现对聚合对象的具体遍历操作。

Aggregate(聚合):定义创建迭代器的接口。

ConcreteAggregate(具体聚合):实现聚合接口,创建具体迭代器对象。

下面是一个示例,展示如何在C#中使用迭代器模式来遍历一个集合对象:

namespace IteratorPattern_迭代器模式
{
    internal class Program
    {
        // Iterator
        public interface IIterator<T>
        {
            bool HasNext();
            T Next();
        }
        // ConcreteIterator
        public class ArrayIterator<T> : IIterator<T>
        {
            private readonly T[] _array;
            private int _index;

            public ArrayIterator(T[] array)
            {
                _array = array;
                _index = 0;
            }

            public bool HasNext()
            {
                return _index < _array.Length;
            }

            public T Next()
            {
                if (_index < _array.Length)
                {
                    return _array[_index++];
                }
                throw new IndexOutOfRangeException();
            }
        }
        // Aggregate
        public interface ICollection<T>
        {
            IIterator<T> CreateIterator();
        }
        // ConcreteAggregate
        public class MyCollection<T> : ICollection<T>
        {
            private readonly T[] _array;

            public MyCollection(T[] array)
            {
                _array = array;
            }
            public IIterator<T> CreateIterator()
            {
                return new ArrayIterator<T>(_array);
            }
        }
        static void Main(string[] args)
        {
            string[] array = new string[] { "A", "B", "C", "D", "E" };
            ICollection<string> collection = new MyCollection<string>(array);
            IIterator<string> iterator = collection.CreateIterator();

            while (iterator.HasNext())
            {
                string element = iterator.Next();
                Console.WriteLine(element);
            }
            Console.Read();
            //输出结果
            //A
            //B
            //C
            //D
            //E
        }
    }
}

在上述示例中,使用迭代器模式实现了一个自定义的集合类(MyCollection)。集合类实现了ICollection接口,其中定义了创建迭代器的方法CreateIterator。具体迭代器(ArrayIterator)实现了IIterator接口,实现了对数组的遍历操作。通过调用集合类的CreateIterator方法,获取一个具体迭代器对象,然后使用迭代器的Next和HasNext方法进行遍历。

在Client中,首先创建了一个字符串数组,并通过集合类的CreateIterator方法获取迭代器对象。然后通过迭代器的Next和HasNext方法遍历并输出每个元素。

迭代器模式使得聚合对象和遍历算法分离,遍历算法被封装在迭代器中,可以在不改变聚合对象的情况下灵活地对其进行遍历。这样可以提高代码的可维护性和可复用性。同时,迭代器模式还可以隐藏聚合对象的内部结构,保护数据的安全性。