直接使用IEnumerator
//-------------------------------------------------------------------------------------
// IteratorExample2.cs
//-------------------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/* Iterator provides uniform way to access different collections of objects
* If you get an Array, ArrayList, Hashtable of objects, you pop out an iterator for each and treat them the same
*
* This provides a uniform way to cycle through different collections
*
* You can also write polymorphic code because you can refer to each collection of objects
* because they'll implement the same interface
* */
public class IteratorExample2 : MonoBehaviour
{
void Start ( )
{
// creating the collections and adding some songs:
USrap usrap = new USrap();
usrap.AddSong("Enemies", "Lose Yourself", 2002);
usrap.AddSong("2Pac", "All Eyez on Me was", 1996);
ChinaRap chrap = new ChinaRap();
chrap.AddSong("周杰伦", "一路向北", 2005);
chrap.AddSong("宋岳庭", "Life Is a Struggle", 2003);
//利用迭代器模式,我们可以用同一个方式遍历两种不同序列,且不用考虑序列内部细节
IEnumerator usrapIterator = usrap.GetIterator();
while (usrapIterator.MoveNext())
{
SongInfo info = (SongInfo)usrapIterator.Current;
Debug.Log("米国rap: " + info.ToStringEx());
}
IEnumerator chinarapIterator = chrap.GetIterator();
while (chinarapIterator.MoveNext())
{
SongInfo info = (SongInfo)chinarapIterator.Current;
Debug.Log("中国rap: " + info.ToStringEx());
}
}
// 歌曲属性类
public class SongInfo
{
public string singer { get; protected set; }
public string songName { get; protected set; }
public int yearReleased { get; protected set; }
public SongInfo(string singer, string songName, int yearReleased)
{
this.singer = singer;
this.songName = songName;
this.yearReleased = yearReleased;
}
public string ToStringEx()
{
return this.singer + " - " + this.songName + " : " + this.yearReleased.ToString();
}
}
// Iterator Interface
public interface SongIterator
{
IEnumerator GetIterator();
}
// 米国rap
public class USrap : SongIterator
{
// 一种用list
protected List<SongInfo> bestSongs;
public USrap()
{
bestSongs = new List<SongInfo>();
}
public void AddSong(string name, string artist, int year)
{
SongInfo song = new SongInfo(name, artist, year);
bestSongs.Add(song);
}
//yield return调用一次返回一次,并且会从当前位置继续
public IEnumerator GetIterator()
{
foreach (SongInfo song in bestSongs)
yield return song;
yield break;
}
}
//中国rap
public class ChinaRap : SongIterator
{
// 一种用数组
protected SongInfo[] bestSongs;
public ChinaRap()
{
bestSongs = new SongInfo[0];
}
public void AddSong(string name, string artist, int year)
{
SongInfo song = new SongInfo(name, artist, year);
//内部细节,迭代器完全不用考虑,这里先把array加入list,再把list转换回array
List<SongInfo> newSongs = new List<SongInfo>(bestSongs);
newSongs.Add(song);
bestSongs = newSongs.ToArray();
}
public IEnumerator GetIterator()
{
foreach (SongInfo song in bestSongs)
yield return song;
yield break;
}
}
}