迭代器模式(Iterator):提供一種方法順序訪問一個彙總對象中各個元素,而又不暴露該對象的內部表示。
迭代器模式結構圖:
typedef String object;
Iterator迭代器抽象類別:
class Iterator
{
public:
virtual object& First()=0;
virtual object& Next()=0;
virtual bool IsDone()=0;
virtual object& CurrentItem()=0;
};
//用於定義得到開始對象,得到下一個對象、判斷是否到結尾、當前對象等抽象方法,統一介面
Aggregate聚集抽象類別:
class Aggregate
{
public:
virtual Iterator* CreateIterator()=0; //建立迭代器
};
ConcreteIterator具體迭代器類,繼承Iterator
class ConcreteIterator :public Iterator
{
private:
ConcreteAggregate * aggregate;
list<object>::iteratorit;
public:
ConcreteIterator(ConcreteAggregate * aggregate)
{
this->aggregate = aggregate;
it=aggregate->begin();
}
object& First()
{
return *it;
}
object& Next()
{
object ret = NULL;
if((++it)!=aggregate->end())
ret = *it;
return ret;
}
bool IsDone()
{
if((++it)!=aggregate->end())
return false;
else
return true;
}
object& CurrentItem()
{
Return *it;
}
};
ConcreteAggregate具體聚集類,繼承Aggregate
class ConcreteAggregate :public Aggregate
{
private:
list<object> *items = new list<object>();
public:
Iterator* CreateIterator()
{
return new ConcreteIterator(ConcreteAggregate *paggregate=this);
}
void setObject(object obj)
{
Items->push_back(obj);
}
};
用戶端代碼:
void main()
{
ConcreteAggregate *pa = newConcreteAggregate();
pa->setObject(“元素1”);
pa->setObject(“元素2”);
pa->setObject(“元素3”);
pa->setObject(“元素4”);
Iterator * it = pa->CreateIteraor(pa);
cout<<it->First();
while(!it->IsDone())
{
cout<<it->CurrentItem()<<endl;
it->Next();
}
}