using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _015迭代器模式
{
/// <summary>
/// 抽象迭代器
/// </summary>
public interface Iterator
{
bool MoveNext();//使指针指向下一位
object GetCurrent();//获取目标物体
void Next();//下移
void Reset();//重置
}
/// <summary>
/// 具体迭代器
/// </summary>
public class GenerateIterator : Iterator
{
private GenerateList mGenerateList;
private int mIndex;
public GenerateIterator(GenerateList generateList)
{
this.mGenerateList = generateList;
mIndex = 0;
}
public object GetCurrent()
{
return mGenerateList.GetElement(mIndex);
}
public bool MoveNext()
{
if (mIndex < mGenerateList.Length)
{
return true;
}
return false;
}
public void Next()
{
if (mIndex < mGenerateList.Length)
{
++mIndex;
}
}
public void Reset()
{
mIndex = 0;
}
}
/// <summary>
/// 抽象聚合对象
/// </summary>
public interface IListColletion
{
Iterator GetIterator();//聚合迭代
}
/// <summary>
/// 具体聚合对象
/// </summary>
public class GenerateList : IListColletion
{
private int[] mElements = new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
public int Length
{
get { return mElements.Length; }
}
public int GetElement(int index)
{
return mElements[index];
}
public Iterator GetIterator()
{
return new GenerateIterator(this);
}
}
internal class Program
{
private static void Main(string[] args)
{
Iterator iter = null;
IListColletion list = new GenerateList();
iter = list.GetIterator();
while (iter.MoveNext())
{
int current = (int)iter.GetCurrent();
Console.WriteLine("----" + current);
iter.Next();
}
Console.ReadKey();
}
}
}