概述
迭代器模式(Iterator):提供一种方法顺次访问聚合对象中各个元素,同时不暴露对象内部细节。
结构图
结构
迭代器抽象类(Iterator):负责定义访问和遍历元素的接口。
定义当前开始对象、得到下一个对象、得到下一个对象、判断是否结尾。将列表的访问和遍历从列表对象中分离,并放到迭代器对象(Iterator)中。
[csharp]
//迭代器抽象类
abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract object IsDone();
public abstract object CurrentItem();
}
具体迭代器(Concrete Iterator):实现迭代器接口,记录遍历中当前位置。
[csharp]
//具体迭代器类,继承Iterator
class ConcreteIterator : Iterator
{
private ConcreteAggregate aggregate;
private int current = 0;
public ConcreteIterator(ConcreteAggregate aggregate)
{
this.aggregate = aggregate;
}
public override object First()
{
return aggregate [0];
}
public override object Next()
{
object ret = null;
current++;
if (current < aggregate.count)
{
ret = aggregate [current];
}
return ret;
}
public override bool IsDone()
{
return current >=aggregate .count ?true:false ;
}
public override object CurrentItem()
{
return aggregate [current ];
}
}
聚集抽象类(Aggregate):提供创建具体迭代器的接口。
[csharp]
//聚集抽象类
abstract class Aggreate
{
public abstract Iterator CreateIterator();
}
具体聚集类(ConcreteAggregate):存放聚合对象,返回聚集的个数并声明一个索引器。
[csharp]
//具体聚集类
class ConcreteAggregate : Aggreate
{
private IList<object > items =new List <object >();
public override Iterator CreateIterator()
{
return new ConcreteIterator(this );
}
public int count
{
get { return items.Count; }
}
public object this[int index]
{
get { return items[index]; }
set { items.Insert(index, value); }
}
}
客户端
[csharp]
static void Main(string[] args)
{
ConcreteAggregate a = new ConcreteAggregate();
a[0] = "persona";
a[1] = "personb";
Iterator i =new ConcreteIterator (a );
object item = i.First();
while (!i.IsDone())
{
Console.WriteLine("{0}请先买票!",i.CurrentItem ());
i.Next();
}
Console.ReadLine();
}