16.迭代器模式
class Program
{
static void Main(string[] args)
{
ConcreteAggregate monkey = new ConcreteAggregate();
monkey[0] = "猴子";
monkey[1] = "刘木同";
monkey[2] = "笨蛋";
monkey[3] = "小弟";
monkey[4] = "领导";
monkey[5] = "内部人员";
monkey[6] = "小偷";
Iterator i = new ConcreteIterator(monkey);
object item = i.First();//从第一个乘客开始
while (!i.IsDone())
{
Console.WriteLine("{0}请买火车票", i.CurrentItem());//若没买票,请补票
i.Next();//遍历下一个
}
Console.Read();
}
}
abstract class Iterator
{
public abstract object First();//1开始对象
public abstract object Next();//2得到下一个对象
public abstract bool IsDone();//3判断是否到结尾
public abstract object CurrentItem();//4当前对象
}
abstract class Aggregate//聚集抽象类
{
public abstract Iterator CreateIterator();//创建迭代器
}
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()//判断当前是否遍历到结尾,到结尾返回true
{
return current >= aggregate.Count ? true : false;
}
public override object CurrentItem()
{
return 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); }
}
}