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

结果

相关推荐
张人玉1 天前
TCP 的三次握手和四次挥手
网络·tcp/ip·c#
曹牧1 天前
C#:三元运算符
开发语言·c#
m0_748248021 天前
C++与C#布尔类型深度解析:从语言设计到跨平台互操作
c++·stm32·c#
LeonDL1681 天前
【通用视觉框架】基于C#+VisionPro开发的视觉框架软件,全套源码,开箱即用
人工智能·c#·visionpro·通用视觉框架·机器视觉框架·视觉框架软件·机器视觉软件
王道长服务器 | 亚马逊云1 天前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
一抓掉一大把1 天前
RuoYi .net-实现商城秒杀下单(redis,rabbitmq)
redis·mysql·c#·rabbitmq·.net
在未来等你1 天前
AI Agent设计模式 Day 1:ReAct模式:推理与行动的完美结合
设计模式·llm·react·ai agent·plan-and-execute
睡前要喝豆奶粉1 天前
在.NET Core Web Api中使用阿里云OSS
阿里云·c#·.netcore
缺点内向2 天前
C#: 高效移动与删除Excel工作表
开发语言·c#·.net·excel
yue0082 天前
C# 分部类读取学生信息
开发语言·c#