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

结果

相关推荐
xiaoshuaishuai819 分钟前
C# 继承与虚方法
开发语言·windows·c#
月昤昽28 分钟前
C#实现AutoCAD旋转与直径标注
c#·.net·二次开发·autocad·autocad二次开发
FL16238631291 小时前
基于C#winform实现yolo26-plate中文车牌检测识别支持12种中文双层颜色车牌文字识别
开发语言·c#
asdfg12589631 小时前
从Java的设计模式看接口和实现---List与ArrayList
java·开发语言·设计模式·面向对象·面向接口
Eiceblue1 小时前
锁定单元格 :C# 控制 Excel 单元格编辑权限
开发语言·c#·excel
菜_小_白1 小时前
高性能线程池
linux·c++·设计模式
我是唐青枫2 小时前
C#.NET YARP 详解:用 ASP.NET Core 打造高性能反向代理网关
c#·.net
小湘西2 小时前
【设计模式】简单工厂、工厂方法、抽象工厂
设计模式
李斯维2 小时前
工厂设计模式(Factory Pattern):工厂方法与抽象工厂的实例演示
java·设计模式
码农翻身2 小时前
设计模式,1994年生,2034卒
设计模式