迭代器模式
迭代器模式:提供一种方法顺序访问一个聚合对象中的各个元素,且不暴露该对象的内部表示。
Unity3D中的迭代器
迭代器模式在Unity游戏开发中用的非常非常多!
.NET框架提供了IEnumerable和IEnumerator接口(写法比GOF的原始版迭代器模式更简洁)
划重点:一个collection要支持Foreach进行遍历,就必须实现IEnumerable,并以某种方式返回迭代器对象:IEnumerator。
Array/ArrayList与迭代器
平常用的最多的Array,ArrayList等就使用了迭代器模式。
- 声明IEnumerable接口(Array—IList—ICollection—IEnumerable)
- 实现IEnumerator
public abstract class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
// GetEnumerator returns an IEnumerator over this Array.
//
// Currently, only one dimensional arrays are supported.
//
public IEnumerator GetEnumerator()
{
int lowerBound = GetLowerBound(0);
if (Rank == 1 && lowerBound == 0)
return new SZArrayEnumerator(this);
else
return new ArrayEnumerator(this, lowerBound, Length);
}
}
Tips:
对于IEnumerable和IEnumerator,FCL提供了泛型和非泛型两大类型。因为非泛型装箱两大问题:和拆箱带来的性能开销问题,所以和泛型集合相比,已经变得越来越鸡肋。两大问题:
-
缺乏类型安全性。它返回object类型的引用