设计模式的理解:迭代器模式(Iterator)
生活随笔
收集整理的這篇文章主要介紹了
设计模式的理解:迭代器模式(Iterator)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ?迭代器模式,又稱游標模式,提供一種方法順序訪問一個集合對象中的各個元素,而又不需要暴露該對象的內部表示。
?
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();} }?
可以通過內部類可是可行的,即把MyIterator類變成MyCollection的內部類實現。為了提高性能,還可以考慮從運行時多態改成編譯時多態。在STL庫中,已經有成熟的迭代器了,比上述代碼的性能更優越,功能更豐富,例如Begin()+n 等操作,反向迭代器等。?但是迭代器的思想沒變,也怎么不復雜。
?
?
總結
以上是生活随笔為你收集整理的设计模式的理解:迭代器模式(Iterator)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式的理解:组合模式 (Compos
- 下一篇: 设计模式的理解: 职责链模式 (Chai