iterator.h
#ifndef ITERATOR_H
#define ITERATOR_H
#include <QString>
class Iterator
{
public:
Iterator() {}
virtual ~Iterator(){}
virtual QString first() = 0;
virtual QString next() = 0;
virtual QString getCur() = 0;
virtual bool isEnd() = 0;
};
#endif // ITERATOR_H
concreteIterator.h
#ifndef CONCRETEITERATOR_H
#define CONCRETEITERATOR_H
#include "iterator.h"
#include "aggregate.h"
class ConcreteIterator : public Iterator
{
public:
ConcreteIterator(Aggregate* pAggregate): m_nCurrent(0),Iterator()
{
m_Aggregate = pAggregate;
}
QString first()
{
return m_Aggregate->pop(0);
}
QString next()
{
QString strRet;
m_nCurrent++;
if(m_nCurrent < m_Aggregate->count())
{
strRet = m_Aggregate->pop(m_nCurrent);
}
return strRet;
}
QString getCur()
{
return m_Aggregate->pop(m_nCurrent);
}
bool isEnd()
{
return ((m_nCurrent >= m_Aggregate->count())) ? true:false;
}
private:
Aggregate* m_Aggregate;
int m_nCurrent;
};
#endif // CONCRETEITERATOR_H
aggregate.h
#ifndef AGGREGATE_H
#define AGGREGATE_H
#include <QString>
#include "iterator.h"
class Aggregate
{
public:
Aggregate() {}
virtual int count() = 0;
virtual void push(const QString& strValue) = 0;
virtual QString pop(const int nIndex) = 0;
virtual Iterator *createIterator() = 0;
};
#endif // AGGREGATE_H
concreteAggregate.h
#ifndef CONCRETEAGGREGATE_H
#define CONCRETEAGGREGATE_H
#include <QVector>
#include <QString>
#include "aggregate.h"
#include "concreteIterator.h"
class ConcreteAggregate : public Aggregate
{
public:
ConcreteAggregate():m_pIterator(NULL)
{
m_vecItems.clear();
}
~ConcreteAggregate()
{
if(NULL != m_pIterator)
{
delete m_pIterator;
m_pIterator = NULL;
}
}
Iterator* createIterator()
{
if(NULL == m_pIterator)
{
m_pIterator = new ConcreteIterator(this);
}
return m_pIterator;
}
int count()
{
return m_vecItems.count();
}
void push(const QString& strValue)
{
m_vecItems.push_back(strValue);
}
QString pop(const int nIndex)
{
QString strRet;
if(nIndex < count())
{
strRet = m_vecItems[nIndex];
}
return strRet;
}
private:
QVector<QString> m_vecItems;
Iterator* m_pIterator;
};
#endif // CONCRETEAGGREGATE_H
main.cpp
#include <QApplication>
#include <QtDebug>
#include "concreteAggregate.h"
#include "iterator.h"
//迭代器模式
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ConcreteAggregate* pName = NULL;
pName = new ConcreteAggregate();
if(NULL != pName)
{
pName->push("hello");
pName->push("word");
}
Iterator* iter = NULL;
iter = pName->createIterator();
if(NULL != iter)
{
QString strItem = iter->first();
qDebug() << strItem;
while (!iter->isEnd())
{
qDebug() << iter->getCur() << " is ok";
iter->next();
}
}
return a.exec();
}
UML
參考:https://www.cnblogs.com/onlycxue/archive/2013/12/25/3490738.html