迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示.
迭代器模式结构图:
foreach in,IEnumerable接口都是为迭代器模式准备的,C#,java等本身已经把这个模式做在语言中了。
迭代器模式实现
Iterator 迭代器抽象类
abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}
Aggregate 聚集抽象类
abstract class Aggregate
{
//创建迭代器
public abstract Iterator CreateIterator();
}
ConcreteIterator具体迭代器类,继承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];
}
}
ConcreteAggregate 具体聚集类,继承Aggregate
class ConcreteAggregate : Aggregate
{
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);}
}
}
---客户端代码---
static void Main(string[] args)
{
ConcreteAggregate a = new ConcreteAggregate();
a[0] = "a1";
a[1] = "a2";
a[2] = "a3";
a[3] = "a4";
a[4] = "a5";
Iterator i = new ConcreteIterator(a);
object item = i.First();
while(!i.IsDone())
{
Console.WriteLine("{}请买票!",i.CurrentItem());
i.Next();
}
Console.Read();
}
在.net中你只要去实现 IEumerator即可实现迭代
迭代器模式就是分离了集合对象遍历行为,抽象出一个迭代器类来负责,这样即可以做到不暴露集合的内部结构,又可以让外部代码透明的地访问集合内部的数据