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

结果

相关推荐
南無忘码至尊2 小时前
Unity C# 入门基础知识点整理与实战技巧
开发语言·c#
蔡蓝3 小时前
设计模式-状态模式
ui·设计模式·状态模式
一只小小汤圆4 小时前
如何xml序列化 和反序列化类中包含的类
xml·开发语言·c#
蔡蓝5 小时前
设计模式-组合模式
java·设计模式·组合模式
wkj0017 小时前
接口实现类向上转型和向上转型解析
java·开发语言·c#
qqxhb7 小时前
零基础设计模式——行为型模式 - 观察者模式
java·观察者模式·设计模式·go
朴shu8 小时前
Avatar-Clipper 轻量级图片裁剪工具
前端·设计模式·开源
C雨后彩虹9 小时前
行为模式-责任链模式
java·设计模式·责任链模式
阿伍.9 小时前
【指针】(适合考研、专升本)
c++·考研·c#
了不起的杰9 小时前
[C++][设计模式] : 单例模式(饿汉和懒汉)
c++·单例模式·设计模式