标签:
一.概述:迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。
二.适用性:
访问一个聚合对象的内容而无需暴露它的内部表示
支持对聚合对象的多种遍历
为遍历不同的聚合结构提供一个统一的接口
三.结构:
迭代器角色(Iterator):迭代器角色负责定义访问和遍历元素的接口
具体迭代器角色(Concrete Iteraror):具体迭代器角色实现了迭代器接口,并需要记录遍历中的当前位置。
聚合角色(Aggregate):聚合角色负责定义获得迭代器角色的接口
具体聚合角色(Concrete Aggregate):具体聚合角色实现聚合角色接口。
四.
/// <summary>
/// 迭代器接口
/// </summary>
public interface Iterator
{
bool MoveNext();
Object GetCurrent();
void Next();
void Reset();
} /// <summary>
/// 抽象聚合接口
/// </summary>
public interface IListCollection
{
/// <summary>
/// 创建迭代器
/// </summary>
/// <returns></returns>
Iterator GetIterator();
} /// <summary>
/// 具体聚合类
/// </summary>
public class ConcreteList:IListCollection
{
int[] collection;
public ConcreteList()
{
collection = new int[] { 1, 2, 3, 4, 5, 6 };
}
/// <summary>
/// 创建迭代器
/// </summary>
/// <returns></returns>
public Iterator GetIterator()
{
return new ConcreteIterator(this);
}
/// <summary>
/// 聚合元素长度
/// </summary>
public int Length { get { return collection.Length; } }
/// <summary>
/// 返回集合元素
/// </summary>
/// <param name="index">索引</param>
/// <returns></returns>
public int GetElement(int index)
{
return collection[index];
}
} /// <summary>
/// 具体迭代器类
/// </summary>
public class ConcreteIterator:Iterator
{
// 迭代器要集合对象进行遍历操作,自然就需要引用集合对象
private ConcreteList _list;
private int _index;
public ConcreteIterator(ConcreteList list)
{
this._list = list;
_index = 0;
}
/// <summary>
/// 遍历条件
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
if (_index < _list.Length)
{
return true;
}
return false;
}
/// <summary>
/// 返回对象
/// </summary>
/// <returns></returns>
public Object GetCurrent()
{
return _list.GetElement(_index);
}
/// <summary>
/// 重置索引
/// </summary>
public void Reset()
{
_index = 0;
}
/// <summary>
/// 移动到下一个索引
/// </summary>
public void Next()
{
if (_index < _list.Length)
{
_index++;
}
}
} /// <summary>
/// C#设计模式-迭代器模式
/// </summary>
class Program
{
static void Main(string[] args)
{
Iterator iterator;
IListCollection list = new ConcreteList();
iterator = list.GetIterator();
while (iterator.MoveNext())
{
int i = (int)iterator.GetCurrent();
Console.WriteLine(i.ToString());
iterator.Next();
}
}
}迭代器模式就是抽象一个迭代器类来分离了集合对象的遍历行为,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据。
优点:迭代器承担了遍历集合的职责
迭代器模式使得访问一个聚合对象的内容而无需暴露它的内部表示,即迭代抽象。
迭代器模式为遍历不同的集合结构提供了一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作
迭代器模式存在的缺陷:
迭代器模式在遍历的同时更改迭代器所在的集合结构会出现异常。使用foreach语句只能在对集合进行遍历,不能在遍历的同时更改集合中的元素。
标签:
原文地址:http://blog.csdn.net/heyangyi_19940703/article/details/51330510