您好,登錄后才能下訂單哦!
interface Iterator
{
object First();
object Next();
bool isDone();
object CurrentItem();
}
class myIterator : Iterator
{
private MyAggragate items;
private int cuttent = 0;
public myIterator(MyAggragate _items)
{
items = _items;
}
public object CurrentItem()
{
return items[cuttent];
}
public object First()
{
return items[0];
}
public bool isDone()
{
return cuttent>=items.Count?true:false;
}
public object Next()
{
cuttent++;
if (cuttent >= items.Count)
return null;
return items[cuttent];
}
}
abstract class Aggragate
{
public abstract Iterator CreateIterator();
}
class MyAggragate : Aggragate
{
private IList<string> list = new List<string>();
public int Count
{
get
{
return list.Count;
}
}
public string this[int index]
{
get
{
return list[index];
}
set
{
list.Insert(index, value);
}
}
public override Iterator CreateIterator()
{
return new myIterator(this);
}
}
//前端
static void Main(string[] args)
{
MyAggragate a = new MyAggragate();
a[0] = "張三";
a[1] = "李四";
a[2] = "王五";
a[3] = "王五2";
diedaiqi.Iterator i = new myIterator(a);
var item = i.First();
Console.WriteLine("{0}1", item);
while (!i.isDone())
{
Console.WriteLine("{0}",i.CurrentItem());
i.Next();
}
Console.ReadLine();
}
總結(jié):訪問(wèn)聚集對(duì)象,不管該對(duì)象是什么,需要遍歷的時(shí)候,就使用迭代器。
迭代器模式:為聚集提供開(kāi)始、下一個(gè)、是否結(jié)束、當(dāng)前處于哪一項(xiàng)的統(tǒng)一的接口。
C#的集合什么的已經(jīng)在內(nèi)部實(shí)現(xiàn)了迭代器。
foreach(string item in a)
{
console.write("當(dāng)前{0}",item);
}的內(nèi)部實(shí)現(xiàn)其實(shí)是:
IEnumerator<string> e=a.GetEnumerator();
while(e.Next())
{
console.write("當(dāng)前{0}",e.Current);
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。