UML类图:
实例实现代码:
abstract class Aggregate { public abstract Iterator CreateIterator(); } 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); } } } abstract class Iterator { public abstract object First(); public abstract object Next(); public abstract bool IsDone(); public abstract object CurrentItem(); } 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 object CurrentItem() { return aggregate[current]; } public override bool IsDone() { return current >= aggregate.Count ? true : false; } } class ConcreteIteratorDesc : Iterator { private ConcreteAggregate aggregate; private int current = 0; public ConcreteIteratorDesc(ConcreteAggregate aggregate) { this.aggregate = aggregate; current = aggregate.Count - 1; } public override object First() { return aggregate[aggregate.Count - 1]; } public override object Next() { object ret = null; current--; if (current >= 0) { ret = aggregate[current]; } return ret; } public override object CurrentItem() { return aggregate[current]; } public override bool IsDone() { return current < 0 ? true : false; } }
客户端实现:
static void Main(string[] args) { ConcreteAggregate a = new ConcreteAggregate(); a[0] = "大鸟"; a[1] = "小菜"; a[2] = "行李"; a[3] = "老外"; a[4] = "公交内部员工"; a[5] = "小偷"; Iterator i = new ConcreteIterator(a); //Iterator i = new ConcreteIteratorDesc(a); object item = i.First(); while (!i.IsDone()) { Console.WriteLine("{0} 请买车票!", i.CurrentItem()); i.Next(); } Console.Read(); }
说明:
提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象的内部表示。
在Cocoa Touch框架中使用迭代器模式:
- iOS开发中的“枚举”就是我们的迭代,基础框架中的NSEnumerator类实现了迭代器模式。抽象NSEnumerator类的私有具体子类返回枚举器对象,能够顺序遍历各种集合---数组,集合,字典,把这些集合中的对象返回给客户端。
- 基于块的枚举,NSArray,NSDictionary,NSSet对象中引入了新方法,用于基于块的枚举,例如- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block;
- 快速枚举。
参考资料
-《大话设计模式》-《Objective-C编程之道》
原文地址:http://blog.csdn.net/junjun150013652/article/details/45502107