标签:迭代器模式
<span style="font-size:18px;">abstract class Aggregate { public abstract Iterator CreateIterator(); }</span>
<span style="font-size:18px;"> abstract class Aggregate { public abstract Iterator CreateIterator(); }</span>
<span style="font-size:18px;">class ConcreteIterator : Iterator { private ConcreteAggregate aggregate; //定义了一个具体聚集对象 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]; //返回当前的聚集对象 } }</span>
<span style="font-size:18px;">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); } //声明一个索引器 } } </span>
<span style="font-size:18px;">static void Main(string[] args) { ConcreteAggregate a = new ConcreteAggregate(); a[0] = "我"; a[1] = "大爷"; a[2] = "行李"; Iterator i = new ConcreteIterator(a); object item = i.First(); while (!i.IsDone()) { Console.WriteLine("{0}请买车票!", i.CurrentItem()); i.Next(); } Console.Read(); } }</span>
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:迭代器模式
原文地址:http://blog.csdn.net/qwlzxx/article/details/46610145