1,動機。
在軟件構建過程中,集合對象內部結構常常變化各異。但對於這些集合對象,我們希望在不暴露其內部結構的同時,可以讓外部客戶代碼透明地訪問其中包含的元素;同時這種“透明遍歷”也爲“
同一種算法在多種集合對象上進行操作”提供了可能。
2,實用性
1.訪問一個聚合對象的內容而無需暴露它的內部表示。
2.支持對聚合對象的多種遍歷。
3.爲遍歷不同的聚合結構提供一個統一的接口(即, 支持多態迭代)。3,生活中的例子:
迭代器提供一種方法順序訪問一個集合對象中各個元素,而又不需要暴露該對象的內部表示。在早期的電視機中,一個撥盤用來改變頻道。當改變頻道時,需要手工轉動撥盤移過每一個頻道,而不論這個頻道是否有信號。現在的電視機,使用[後一個]和[前一個]按鈕。當按下[後一個]按鈕時,將切換到下一個預置的頻道。想象一下在陌生的城市中的旅店中看電視。當改變頻道時,重要的不是幾頻道,而是節目內容。如果對一個頻道的節目不感興趣,那麼可以換下一個頻道,而不需要知道它是幾頻道。
4,代碼實現
using System;
using UnityEngine;
/// <summary>
/// 抽象聚集
/// </summary>
public interface IList
{
Iterator GetIterator();
}
/// <summary>
/// 抽象迭代器
/// </summary>
public interface Iterator
{
bool MoveNext();
object CurrentItem();
void First();
void Next();
}
public class ConcreateList : IList{
int [] list;
public ConcreateList()
{
list = new int[] { 1,2,3,4,5};
}
public Iterator GetIterator()
{
return new ConcreateIterator (this);
}
public int Length
{
get{ return list.Length; }
}
public int GetElement(int index)
{
return list[index];
}
}
public class ConcreateIterator : Iterator
{
private ConcreateList list;
private int index;
public ConcreateIterator(ConcreateList list)
{
this.list = list;
index = 0;
}
public bool MoveNext()
{
if (index < list.Length) {
return true;
} else {
return false;
}
}
public object CurrentItem()
{
return list.GetElement (index);
}
public void First()
{
index = 0;
}
public void Next()
{
if (index < list.Length) {
index++;
}
}
}
class ProgramMain
{
static void ProMain(string[] args)
{
Iterator iterator;
IList list = new ConcreateList ();
iterator = list.GetIterator ();
while(iterator.MoveNext())
{
int i = (int)iterator.CurrentItem ();
Debug.Log ("item id :"+i.ToString());
iterator.Next ();
}
}
}