【C#设计模式(17)——迭代器模式(Iterator Pattern)】

发布于:2024-12-09 ⋅ 阅读:(174) ⋅ 点赞:(0)

前言

迭代器模式可以使用统一的接口来遍历不同类型的集合对象,而不需要关心其内部的具体实现。

代码

//迭代器接口
public interface Iterator
{
    bool HashNext();
    object Next();
}
//集合接口
public interface Collection
{
    Iterator CreateIterator();
}
//元素迭代器
public class ElementIterator : Iterator
{
    private string[] elements;
    private int index = 0;
    
    public ElementIterator(string[] elements)
    {
        this.elements = elements;
    }

    public bool HashNext()
    {
        return index < elements.Length;
    }

    public object Next()
    {
        if (index < elements.Length)
        {
            return elements[index++];
        }
        return null;
    }
}

//元素集合
public class ElementCollection : Collection
{
    private string[] elements;
    public ElementCollection(string[] elements)
    {
        this.elements = elements;
    }

    public Iterator CreateIterator()
    {
        return new ElementIterator(elements);
    }
}

/*
 * 行为型模式:Behavioral Pattern 
 * 迭代器模式:Iterator Pattern
 */
internal class Program
{
    static void Main(string[] args)
    {
        string[] elements = { "A", "B", "C", "D", "E", "F",};

        Collection collection = new ElementCollection(elements);
        Iterator iterator = collection.CreateIterator();
        while(iterator.HashNext())
        {
            Console.WriteLine(iterator.Next().ToString());
        }
        Console.ReadLine();
    }
}

结果

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到