迭代器模式【大话设计模式DEMO】

 

代码
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 CreateIterator();
}

class ConcreteIterator : Iterator
{
private ConcreteAggregate aggregate;
private int current = 0;
public ConcreteIterator(ConcreteAggregate agg)
{
this.aggregate = agg;
}
public override object First()
{
return this.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 this.aggregate[current];
}
}

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()
{
ConcreteAggregate a
= new ConcreteAggregate();
a[
0] = "a";
a[
1] = "b";
a[
2] = "c";
a[
3] = "d";
a[
4] = "e";
a[
5] = "f";
Iterator i
= new ConcreteIterator(a);
object item = i.First();
while(!i.IsDone())
{
Console.WriteLine(i.CurrentItem());
i.Next();
}
Console.Read();
}

 

posted @ 2010-04-05 21:41  chunchill  阅读(262)  评论(0编辑  收藏  举报