http://blog.youkuaiyun.com/lcl_data/article/details/9310313
http://www.cnblogs.com/onlycxue/archive/2013/12/25/3490738.html
迭代器模式
特点:
提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
角色:
迭代器角色(Iterator):迭代器角色负责定义访问和遍历元素的接口。
具体迭代器角色(Concrete Iterator):具体迭代器角色要实现迭代器接口,并要记录遍历中的当前位置。
集合角色(Aggregate):集合角色负责提供创建具体迭代器角色的接口。
具体集合角色(Concrete Aggregate):具体集合角色实现创建具体迭代器角色的接口——这个具体迭代器角色和该集合的结构相关。
要点:一方面集合创建迭代器;另一方面创建迭代器的同时将集合自己this指针传给了迭代器,使得迭代器拥有这个集合的指针,从而可以访问这个集合。
是
const int Size=5;
template<class T>
class Iterator{
public:
virtual void First()=0;
virtual void Next()=0;
virtual bool IsDone()=0;
virtual T CurrentItem()=0;
};
template<class T>
class Aggregate{
public:
Aggregate(){
for(int i=0;i<Size;++i)
object[i]=i;
}
virtual Iterator<T>* CreateIterator()=0;
virtual T GetItem(int index)=0;
virtual int GetSize()=0;
protected:
T object[Size];
};
template<class T>
class ConcreteIterator: public Iterator<T>{
public:
ConcreteIterator(Aggregate<T>* ag){
cur=0;
m_ag=ag;
}
void First(){
cur=0;
}
void Next(){
if(cur< m_ag->GetSize())
cur++;
}
bool IsDone(){
return cur==m_ag->GetSize();
}
T CurrentItem(){
return m_ag->GetItem(cur);
}
private:
int cur;
Aggregate<T>* m_ag;
};
template<class T>
class ConcreteAggregate:public Aggregate<T>{
public:
<strong> Iterator<T>* CreateIterator(){
return new ConcreteIterator<T>(this);// 迭代器被谁创建就持有谁的引用
}</strong>
T GetItem(int index){
return object[index];
}
int GetSize(){
return Size;
}
};
int main(){
Aggregate<int>* a=NULL;
Iterator<int>* ite=NULL;
a=new ConcreteAggregate<int>;
ite=a->CreateIterator();
for(;!(ite->IsDone());ite->Next())
cout<<ite->CurrentItem()<<' '<<endl;
delete a;
delete ite;
return 0;
}