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

结果

相关推荐
bugcome_com3 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中4 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
bugcome_com6 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
BD_Marathon7 小时前
设计模式——合成复用原则
设计模式·合成复用原则
懒人咖16 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com17 小时前
深入了解 C# 编程环境及其开发工具
c#
书院门前细致的苹果17 小时前
设计模式大全:单例、工厂模式、策略模式、责任链模式
设计模式·责任链模式·策略模式
wfserial19 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师20 小时前
INote轻量文本编辑器
java·javascript·python·c#
kylezhao201921 小时前
C# 中的 SOLID 五大设计原则
开发语言·c#