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

前言

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

代码

csharp 复制代码
//迭代器接口
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();
    }
}

结果

相关推荐
de之梦-御风23 分钟前
【Winform】实现“下拉自动补全”通常指的是 ComboBox / TextBox 在输入时自动提示或补全匹配项
c#
m5655bj39 分钟前
如何通过 C# 快速生成二维码 QR Code
c#·visual studio
浩子智控1 小时前
开源RPA选择
python·c#·软件工程
胖虎11 小时前
iOS中的设计模式(十)- 中介者模式(从播放器场景理解中介者模式)
设计模式·中介者模式·解耦·ios中的设计模式
Geoking.1 小时前
【设计模式】组合模式(Composite)详解
java·设计模式·组合模式
刀法孜然1 小时前
23种设计模式 3 行为型模式 之3.6 mediator 中介者模式
设计模式·中介者模式
缺点内向1 小时前
C#: 如何自动化创建Word可填写表单,告别手动填写时代
c#·自动化·word
阿蒙Amon2 小时前
C#每日面试题-Array和List的区别
面试·c#
SunnyDays10112 小时前
如何使用 C# 将 PDF 转换为 SVG:完整指南
c#·pdf转svg
Lv11770082 小时前
Visual Studio中的正则表达式
ide·笔记·正则表达式·c#·visual studio