迭代器模式
迭代器模式, 提供一种方法顺序访问一个聚合对象中各个元素, 而又不暴露该对象的内部表示.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| abstract class Iterator { public abstract object First(); public abstract object Next(); public abstract bool IsDone(); public abstract object CurrentItem(); }
abstract classs Aggregate { public abstract Iterator CreateIterator(); }
class ConcreteTerator : 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]; } retrun ret; }
public override bool IsDone() { return current >= aggregate.Count; }
public override object CurrentItem() { return aggregate[current]; } }
class ConcreteAggregate : Aggregate { private IList<object> items = new IList<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); } } }
|