设计模式- 迭代器模式
Gof定义
提供一种方法顺序访问一个聚合对象中的各个元素, 而又不暴露该对象的内部表示。
理解
我们实际上经常用到迭代器模式,例如FOREACH语句,就是对迭代器模式的实现,泛型像LIST也是对迭代器模式的实现。关于迭代器模式在实际应用中很广泛,但他已经渐渐的融入到我们的编程语言语法中的其中一部份,所以实际上可能不需要再自己要动手写一个迭代器模式了。
但是大概去了解一下内部实现原理,我觉的还是很值得的。
示例代码
View Code
/// <summary> /// 集合结构接口 /// </summary> public interface Aggregate { Iterator CreateIterator(); } /// <summary> /// 迭代器接口 /// </summary> public interface Iterator { object First(); object Next(); bool IsDone(); object CurrentItem(); } /// <summary> /// 集合结构的具体类 /// </summary> class ConcreteAggregate : Aggregate { private List<object> items = new List<object>(); public 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); } } } /// <summary> /// 具体的迭代器类 /// </summary> class ConcreteIterator : Iterator { private ConcreteAggregate _aggregate; private int _current = 0; public ConcreteIterator(ConcreteAggregate aggregate) { this._aggregate = aggregate; } public object First() { return _aggregate[0]; } public object Next() { object r = null; _current++; if (_current < _aggregate.Count) { r = _aggregate[_current]; } return r; } public bool IsDone() { return _current >= _aggregate.Count ? true : false; } public object CurrentItem() { return _aggregate[_current]; } } /// <summary> /// 客户端调用 /// </summary> class Program { static void Main(string[] args) { ConcreteAggregate ca = new ConcreteAggregate(); ca[0] = "AspNet3.5 揭秘"; ca[0] = "重构:改善既有代码的设计"; ca[2] = "设计模式"; ca[3] = "人月神话"; ca[4] = "代码大全2"; Iterator i = new ConcreteIterator(ca); while (!i.IsDone()) { Console.WriteLine("要读的书:" + i.CurrentItem()); i.Next(); } } }
去掉Aggregate类,简单实现
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ConcreteAggregate ca = new ConcreteAggregate(); ca[0] = "高等数学"; ca[1] = "C语言程序设计"; ca[2] = "操作系统"; ca[3] = "数据结构"; ca[4] = "算法原理"; ca[5] = "编译原理"; Iterator i = new ConcreteIterator(ca); while (i.IsDone()) { Console.WriteLine("要读的书:" + i.CurrentItem()); i.Next(); } Console.ReadLine(); } } public interface Iterator { object First(); void Next(); bool IsDone(); object CurrentItem(); } class ConcreteAggregate { private List<object> items = new List<object>(); public int Count { get { return items.Count; } } public object this[int index] { get { return items[index]; } set { items.Insert(index, value); } } } class ConcreteIterator : Iterator { private ConcreteAggregate _aggregate; private int _current = 0; public ConcreteIterator(ConcreteAggregate aggregate) { this._aggregate = aggregate; } public object First() { return _aggregate[0]; } public void Next() { if(_current < _aggregate.Count) _current++; } public bool IsDone() { if (_current < _aggregate.Count) { return true; } else { return false; } } public object CurrentItem() { return _aggregate[_current]; } } }