迭代器模式(Iterator)

2021-09-11 03:32:32 字數 1707 閱讀 8156

c# 中已經實現了迭代器功能, foreach in 和 ienumerable 和 ieumerator 介面 是為迭代器而準備的。 所以在實用性上已經沒有了。

1.提供一種方法順序訪問乙個聚合物件中各個元素,而又不暴露該物件的內部表示。

2.當訪問乙個聚集物件,而且不管這些物件是什麼都需要遍歷的時候,你就應該考慮用迭代器模式。

3.遍歷的方式可以從頭到尾,也可以從尾到頭的選擇。

4.為遍歷不同的聚集結構提供如開始、下乙個、是否結束、當前哪一項等統一的介面。

5. 迭代器模式就是分離了集合物件的遍歷行為,抽象出乙個迭代器類來負責,這樣既可以做到不暴露集合的內部結構,又可讓外部**透明地訪問集合內部的資料。

歷史實現迭代器

using system;

using system.collections.generic;

using system.text;

namespace 迭代器模式

請買車票!", i.currentitem());

i.next();

}console.read();}}

abstract class

aggregate

class

concreteaggregate : aggregate

public int count

}public object this[int index]

set }}

abstract class

iterator

class

concreteiterator : iterator

public override object first()

public override object next()

return ret;

}public override object currentitem()

public override bool isdone()

}class

concreteiteratordesc : iterator

public override object first()

public override object next()

return ret;

}public override object currentitem()

public override bool isdone()}}

迭代器的.net 實現

using system;

using system.collections.generic;

using system.text;

namespace 迭代器模式

請買車票!", item);

}//上面 foreach in 所實現的操作如下

ienumerator

e = a.getenumerator();

while (e.movenext())

請買車票!", e.current);

}console.read();}}

}

posted on

2009-12-06 16:48

...)

編輯收藏

迭代器模式(Iterator)

迭代器模式 iterator 提供一種方法順序訪問乙個聚合物件中的各種元素,而又不暴露該物件的內部表示。當你需要訪問乙個聚合物件,而且不管這些物件是什麼都需要遍歷的時候,就應該考慮使用迭代器模式。另外,當需要對聚集有多種方式遍歷時,可以考慮去使用迭代器模式。迭代器模式為遍歷不同的聚集結構提供如開始 ...

迭代器模式(Iterator)

1.目的 當需要遍歷 單種方式或多種方式 遍歷乙個組合物件時,使用遍歷模式。該模式類似與將容器的介面進行封裝,不對外直接暴露容器的介面的做法類似。2.ifndef iterator h define iterator h include include using namespace std cla...

Iterator 迭代器模式

現在有乙個集合。其內部元素的儲存方式可能比較複雜。為了讓使用者在不用關心其內部表示的情況下對其元素進行訪問,於是建立了乙個迭代器用於對集合的各個元素進行訪問。為了給使用者提供乙個更友好且強大的介面類,於是對迭代器以組合的形式進行封裝,得到乙個管理類。使用者直接操作該管理類即可得到指定元素,或通過管理...