C++设计模式---迭代器模式
迭代器模式(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 : 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 : 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();
}
}