前置文章: 设计模式的原则
其他设计模式:用心理解设计模式
设计模式相关代码已统一放至 我的 Github
一、定义
行为型模式之一。
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
(提供按顺序依次访问容器中元素的方法,而不暴露其底层表示(内部结构)。)
二、结构解析
迭代器模式的一般结构有四种角色: 抽象迭代器、抽象容器、具体迭代器。
抽象迭代器(Iterator):抽象游标,负责定义访问和遍历元素的接口。获取当前迭代位置的值(必要)、向下一个位置移动(必要)、回到起始位置(可选)、迭代是否完成(可选)等。
抽象容器(Aggregate):负责定义一个获取迭代器的接口。
具体迭代器(ConcreteIterator):具体游标,实现抽象迭代器定义的接口,
具体容器(ConcreteAggregate):实现自身容器结构、实现获取迭代器的接口(没有时先创建),持有并使用获取到的迭代器对容器中的元素进行遍历。
三、评价
迭代器模式是为各种不同结构的容器 “顺序访问内部元素” 提供的一个通用方案。
使用了迭代器模式的容器,客户在对其遍历时,只需使用迭代器提供的接口即可,不用再关心容器的内部结构(对外隐藏了容器的内部结构)。
C#中的容器广泛使用了迭代器模式,参考 IEnumerator 和 IEnumerable。
四、实现
自己实现List并使用迭代器模式。
using System.Collections.Generic;
using UnityEngine;
namespace Iterator
{
public interface Iterator
{
object Current();
bool Next();
}
public interface Aggregate
{
Iterator GetIterator();
}
public class ConcreateIterator : Iterator
{
private ConcreateAggregate integerList;
private int index;
public ConcreateIterator(ConcreateAggregate integerList)
{
this.integerList = integerList;
this.index = 0;
}
public object Current()
{
return integerList.Get(index);
}
public bool Next()
{
index += 1;
if (index < integerList.Count)
{
return true;
}
//重置
index = 0;
return false;
}
}
//自己实现简单的string类型的list示例
public class ConcreateAggregate : Aggregate
{
private string[] array;
private int count;
ConcreateIterator concreateIterator;
public ConcreateAggregate()
{
count = 0;
array = new string[1];
}
public Iterator GetIterator()
{
if (concreateIterator == null)
{
concreateIterator = new ConcreateIterator(this);
}
return concreateIterator;
}
public int Count
{
get
{
return count;
}
}
public void Add(string element)
{
if (count == array.Length)
{
string[] newArray = new string[count * 2];
array.CopyTo(newArray, 0);
array = newArray;
}
array[count] = element;
count += 1;
}
public string Get(int index)
{
return array[index];
}
}
public class Client
{
static public void Main()
{
ConcreateAggregate list = new ConcreateAggregate();
list.Add("N");
list.Add("R");
list.Add("a");
list.Add("t");
list.Add("e");
list.Add("l");
Iterator iterator = list.GetIterator();
do
{
Debug.Log(iterator.Current());
}
while (iterator.Next());
}
}
}