3_4 IteratorMode 迭代器模式
生活随笔
收集整理的這篇文章主要介紹了
3_4 IteratorMode 迭代器模式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
// 定義:提供一種方法順序當(dāng)問一個(gè)聚合對象中的各個(gè)元素,而不
// 暴露該對象的內(nèi)部表示
//
// 模式舉例:
//
// 模式特點(diǎn):
//
//#include<iostream>
#include<string>
#include<vector>
using namespace std;//迭代器
class Iterator
{
public:virtual string first()=0;virtual string next()=0;virtual string getCur()=0;virtual bool isEnd()=0;
};//pop肯定要是彈出元素啦!!!//聚合對象
class Aggregate
{
public:virtual void push(string s)=0;virtual string pop(int pos)=0;virtual string getValue(int pos)=0;virtual int count()=0;virtual Iterator * createIterator()=0;
};class ConcreteIterator : public Iterator
{
public:ConcreteIterator(Aggregate *a){m_aggregate = a;m_curPos = 0;}virtual string first(){return m_aggregate->getValue(0);}virtual string next(){m_curPos ++;if(m_curPos < m_aggregate->count()){return m_aggregate->getValue(m_curPos);}else{return "";}}virtual string getCur(){return m_aggregate->getValue(m_curPos);}virtual bool isEnd(){return m_curPos==m_aggregate->count();}private:Aggregate * m_aggregate;int m_curPos;
};class ConcreteAggregate : public Aggregate
{
public:ConcreteAggregate(){m_iter = NULL;}virtual void push(string s){m_strvec.push_back(s);}virtual string pop(int pos){string str = m_strvec[pos];m_strvec.erase(pos);return str;}virtual string getValue(int pos){return m_strvec[pos];}virtual int count(){return m_strvec.size();}virtual Iterator * createIterator(){if(m_iter==NULL){m_iter = new ConcreteIterator(this);}return m_iter;}private:vector<string> m_strvec;Iterator * m_iter;
};int main()
{Aggregate * pAggregate = new ConcreteAggregate();Iterator * iter = pAggregate->createIterator();pAggregate->push("test1");pAggregate->push("test2");pAggregate->push("test3");while(!iter->isEnd()){cout<<iter->getCur()<<endl;iter->next();}return 0;
}
?
總結(jié)
以上是生活随笔為你收集整理的3_4 IteratorMode 迭代器模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++字符串操作函数
- 下一篇: sscanf函数用法详解