设计模式的理解:迭代器模式(Iterator)
生活随笔
收集整理的這篇文章主要介紹了
设计模式的理解:迭代器模式(Iterator)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ?迭代器模式,又稱(chēng)游標(biāo)模式,提供一種方法順序訪(fǎng)問(wèn)一個(gè)集合對(duì)象中的各個(gè)元素,而又不需要暴露該對(duì)象的內(nèi)部表示。
?
template<typename T> class Iterator{public :vitrual void first() = 0;vitrual void next() = 0;vitrual bool isDone() = 0;vitrual T& currentItem() = 0; }template<typename T> class Aggregate{public :Iterator<T> getIterator()=0; }template<typename T> class MyIterator: public Iterator<T>{ private :MyCollection<T> mc;public :MyIterator(const MyCollection<T> &c):mc(c){}vitrual void first(){...}vitrual void next() {...}vitrual bool isDone() {...}vitrual T& currentItem() {...} }template<typename T> class MyCollection: public Aggregate{public :Iterator<T> getIterator(){ return MyIterator(*this);}..... }void main(){MyCollection<int> myCollection;....Iterator<int> iterator = myCollection.getIterator();for(iterator.first();iterator.isDone();iterator.next()){cout<<"currentItem:"<<iterator.currentItem();} }?
可以通過(guò)內(nèi)部類(lèi)可是可行的,即把MyIterator類(lèi)變成MyCollection的內(nèi)部類(lèi)實(shí)現(xiàn)。為了提高性能,還可以考慮從運(yùn)行時(shí)多態(tài)改成編譯時(shí)多態(tài)。在STL庫(kù)中,已經(jīng)有成熟的迭代器了,比上述代碼的性能更優(yōu)越,功能更豐富,例如Begin()+n 等操作,反向迭代器等。?但是迭代器的思想沒(méi)變,也怎么不復(fù)雜。
?
?
總結(jié)
以上是生活随笔為你收集整理的设计模式的理解:迭代器模式(Iterator)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 设计模式的理解:组合模式 (Compos
- 下一篇: 设计模式的理解: 职责链模式 (Chai