提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
当你需要访问一个聚集对象,而且不管这些对象是什么都需要遍历的时候,就应该考虑用迭代器模式。
//定义一个迭代器抽象类
//迭代器抽象类
abstract class Iterator
{
//用于定义得到开始对象,得到下一个对象、判断是否到结尾、当前对象等抽象方法,统一接口。
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}
//聚集抽象类
abstract class Aggregate
{
//创建迭代器
public abstract Iterator CreateIterrator();
}
class ConcreteAggregate : Aggregate
{
//声明一个IList泛型变量,用于存放聚合对象。
IList<object> items = new List<object>();
public override Iterator CreateIterrator()
{
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); }
}
}
//具体迭代器类,继承Iterator
class ConcreteIterator : Iterator
{
ConcreteAggregate aggregate;
int current = 0;
public ConcreteIterator(ConcreteAggregate aggregate)
{
this.aggregate = aggregate;
}
public override object CurrentItem()
{
return aggregate[current];
}
public override object First()
{
return aggregate[0];
}
public override bool IsDone()
{
return current >= aggregate.Count ? true : false;
}
public override object Next()
{
object obj = null;
current++;
if(current<aggregate.Count)
{
obj = aggregate[current];
}
return obj;
}
}
调用:
ConcreteAggregate aggres = new ConcreteAggregate();
aggres[0] = "dd";
aggres[1] = "aa";
aggres[2] = "cc";
Iterator it = new ConcreteIterator(aggres);
while (!it.IsDone())
{
Console.WriteLine(it.CurrentItem());
it.Next();
}
倒序
改写或添加具体迭代器类
class ConcreteIteratorDesc : Iterator
{
ConcreteAggregate aggregate;
int current = 0;
public ConcreteIteratorDesc(ConcreteAggregate aggre)
{
this.aggregate = aggre;
this.current = aggre.Count-1;
}
public override object CurrentItem()
{
return aggregate[current];
}
public override object First()
{
return aggregate[this.aggregate.Count-1];
}
public override bool IsDone()
{
return current < 0 ? true : false;
}
public override object Next()
{
object obj = null;
current--;
if (current >= 0)
{
obj = aggregate[current];
}
return obj;
}
}
调用:
改写下Iterator的实例为ConcreteIteratorDesc就可以了
Iterator it = new ConcreteIterator(aggres);
原文:http://www.cnblogs.com/buzhidaojiaoshenme/p/6731440.html