# 迭代器模式
属于行为型模式。
提供一种方法顺序访问一个聚合对象中各个元素,而又无须暴露该对象的内部表示。
现在,迭代器模式的实用价值远不如学习价值了,因为现在的高级编程语言已经把这个模式做在语言中了。CSharp 中的迭代器就是一个例子。
接下来讲解的内容不是传统的迭代器模式,而是复刻 foreach 的功能。
# 类图
# 代码
# 用于测试的类
namespace BehavioralPatterns_IteratorPattern | |
{ | |
public class Shape | |
{ | |
public string Name; | |
public Shape(string name) | |
{ | |
Name = name; | |
} | |
} | |
} |
# 复刻 foreach 的功能
namespace BehavioralPatterns_IteratorPattern | |
{ | |
public static class ArrayIterator | |
{ | |
/// <summary> | |
/// 遍历 | |
/// </summary> | |
/// <typeparam name="T"> 数据类型 & lt;/typeparam> | |
/// <param name="targets"> 需要遍历的数组 & lt;/param> | |
/// <param name="action"> 遍历方法 & lt;/param> | |
public static void Iterate<T>(this T[] targets, Action<T> action) | |
{ | |
for (int i = 0; i < targets.Length; i++) | |
{ | |
action(targets[i]); | |
} | |
} | |
/// <summary> | |
/// 遍历列表 | |
/// </summary> | |
/// <typeparam name="T"> 数据类型 & lt;/typeparam> | |
/// <param name="targets"> 需要遍历的列表 & lt;/param> | |
/// <param name="action"> 遍历方法 & lt;/param> | |
public static void Iterate<T>(this List<T> targets, Action<T> action) | |
{ | |
for (int i = 0; i < targets.Count; i++) | |
{ | |
action(targets[i]); | |
} | |
} | |
} | |
} |
# 测试
namespace BehavioralPatterns_IteratorPattern | |
{ | |
public class Program | |
{ | |
private static void Main() | |
{ | |
Shape[] shapes = new Shape[] | |
{ | |
new Shape("shapes_0"), | |
new Shape("shapes_1"), | |
}; | |
shapes.Iterate(shape => { Console.WriteLine(shape.Name); }); | |
Console.WriteLine(); | |
List<Shape> shapeList = new List<Shape> | |
{ | |
new Shape("shapes_2"), | |
new Shape("shapes_3"), | |
}; | |
shapeList.Iterate(shape => { Console.WriteLine(shape.Name); }); | |
} | |
} | |
} |
运行结果:
shapes_0
shapes_1
shapes_2
shapes_3