标题: 模式设计之迭代器 [打印本页] 作者: の瘋がす贪恋 时间: 2009-11-6 01:35 标题: 模式设计之迭代器 using System;
using System.Collections.Generic;
using System.Text;
namespace _0090901
{
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 CreatIterator();
}
class ConcreateIterator : Iterator
{
private ConcreateAggregate aggregate;
private int current = 0;
public ConcreateIterator(ConcreateAggregate 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];
}
};
class ConcreateAggregate : Aggregate
{
private IList<object> items = new List<object>();
public override Iterator CreatIterator()
{
return new ConcreateIterator(this);
}
public int Count
{
get { return items.Count; }
}
public object this[int index]
{
get { return items[index]; }
set { items.Insert(index, value); }
}
}
class Program
{
static void Main(string[] args)
{
ConcreateAggregate a = new ConcreateAggregate();
a[0] = "大鸟";
a[1] = "小菜";
a[2] = "行李";
a[3] = "老外";
a[4] = "公交内部员工";
a[5] = "小偷";
Iterator i = new ConcreateIterator(a);
object item = i.First();
while (!i.IsDone())
{
Console.WriteLine("{0}请买票!", i.CurrentItem());
i.Next();
}
Console.Read();
}
}
}
23个模式很经典,最近一直在自己写着玩玩,没事贴点,怀恋我还是在写代码的。。哎。。