迭代器模式(Iterator Pattern)部分代码

摘自TerryLee's Blog
URL:http://www.cnblogs.com/Terrylee/archive/2006/09/16/Iterator_Pattern.html

public interface IList
{
    IIterator GetIIterator();
}
public interface IIterator
{
    bool MoveNext();
    object CurrentItem();
    void First();
    void Next();
}

class ConcreateList : IList
{
    int[] list;
    public ConcreateList()
    {
        list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    }

    //实现接口方法
    public IIterator GetIIterator()
    {
        return new ConcreteIterator(this);
    }
   
    public int Length
    {
        get { return list.Length; }
    }

    public int GetElement(int index)
    {
        return list[index];
    }


}
class ConcreteIterator : IIterator
{
    //声明聚集
    private ConcreateList list;
    //声明索引
    private int index;

    public ConcreteIterator(ConcreateList lst)
    {
        this.list = lst;
        this.index = 0;
    }
    /// <summary>
    /// 表示是否可以向后移动
    /// </summary>
    /// <returns>bool true:表示可以移动</returns>
    public bool MoveNext()
    {
        if (index < list.Length)
        {
            return true;
        }
        else
        {
            return false;
        }

    }
    public object CurrentItem()
    {
        return list.GetElement(index);
    }
    public void First()
    {
        index = 0;
    }
    public void Next()
    {
        if (index < list.Length)
        {
            index++;
        }
    }


}


class App
{
    public static void Main()
    {
        //实例化聚集
        IList lst = new ConcreateList();
        IIterator iteraotr = lst.GetIIterator();
        while (iteraotr.MoveNext())
        {
            int i = (int)iteraotr.CurrentItem();
            System.Console.WriteLine(i.ToString());
            iteraotr.Next();
        }
        System.Console.ReadLine();
    }
   
   
}

 

你可能感兴趣的:(iterator)