【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();
    }
}

结果

相关推荐
csdn_aspnet8 小时前
浅谈 C# 与 Data URI
c#
烛阴9 小时前
C# 正则表达式:量词与锚点——从“.*”到精确匹配
前端·正则表达式·c#
云中飞鸿11 小时前
值类型、引用类型
c#
c#上位机13 小时前
halcon窗口显示文字
图像处理·c#·halcon
kingwebo'sZone13 小时前
Datagridview 显示当前选中行
c#
时光追逐者15 小时前
一个基于 .NET 开源、功能强大的分布式微服务开发框架
分布式·微服务·开源·c#·.net·.net core
Poetinthedusk15 小时前
设计模式-命令模式
windows·设计模式·c#·wpf·命令模式
雨中飘荡的记忆16 小时前
设计模式之桥接模式:从原理到实战
设计模式
北海屿鹿16 小时前
设计模式概述
设计模式
csdn_aspnet18 小时前
C# 电子签名及文档存储
javascript·c#