概念
迭代模式是行爲模式之一,它把對容器中包含的內部對象的訪問委讓給外部類,使用Iterator(遍歷)按順序進行遍歷訪問的設計模式。
在應用Iterator模式之前,首先應該明白Iterator模式用來解決什麼問題。或者說,如果不使用Iterator模式,會存在什麼問題。
1.由容器自己實現順序遍歷。直接在容器類裏直接添加順序遍歷方法
2.讓調用者自己實現遍歷。直接暴露數據細節給外部。
以上方法1與方法2都可以實現對遍歷,這樣有問題呢?
1,容器類承擔了太多功能:一方面需要提供添加刪除等本身應有的功能;一方面還需要提供遍歷訪問功能。
2,往往容器在實現遍歷的過程中,需要保存遍歷狀態,當跟元素的添加刪除等功能夾雜在一起,很容易引起混亂和程序運行錯誤等。
Iterator模式就是爲了有效地處理按順序進行遍歷訪問的一種設計模式,簡單地說,Iterator模式提供一種有效的方法,可以屏蔽聚集對象集合的容器類的實現細節,而能對容器內包含的對象元素按順序進行有效的遍歷訪問。所以,Iterator模式的應用場景可以歸納爲滿足以下幾個條件:
1.訪問容器中包含的內部對象;2.按順序訪問
角色和職責
提供一種方法順序訪問一個聚斂對象的各個元素,而又不暴露該對象的內部表示。爲遍歷不同的聚集結構提供如開始,下一個,是否結束,當前一項等統一接口。在迭代器中持有 一個集合的引用;所以通過迭代器,就可以訪問集合。
Iterator(迭代器接口):該接口必須定義實現迭代功能的最小定義方法集,比如提供hasNext()和next()方法。
ConcreteIterator(迭代器實現類):迭代器接口Iterator的實現類。可以根據具體情況加以實現。
Aggregate(容器接口):定義基本功能以及提供類似Iterator iterator()的方法。
concreteAggregate(容器實現類):容器接口的實現類。必須實現Iterator iterator()方法。
案例
#include <iostream>
using namespace std;
typedef int Object ;
#define SIZE 5
class Aggregate
{
public:
virtual Object getItem(int index) = 0;
virtual MyIterator* CreateIterator() = 0;
virtual int getSize() = 0;
};
class MyIterator
{
public:
virtual void First() = 0;
virtual void Next() = 0;
virtual bool IsDone() = 0;
virtual Object Currentitem() = 0
};
class ConterteIterator:public MyIterator
{
public:
ConterteIterator(Aggregate *ag)
{
m_ag = ag;
m_idx = 0;
}
~ConterteIterator()
{
m_ag = NULL;
m_idx = 0;
}
virtual void First()
{
m_idx = 0;
}
virtual void Next()
{
if (_idx <m_ag->getSize())
{
m_idx++;
}
}
virtual bool IsDone()
{
return (m_idx == m_ag->getSize());
}
virtual Object Currentitem()
{
return _ag->getItem(_idx);
}
private:
int m_idx;
Aggregate *m_ag;
};
class ConcreteAggrete:public Aggregate
{
public:
ConcreteAggregate()
{
for (int i=0; i<SIZE; i++)
{
object[i] = i+1;
}
}
virtual ~ConcreteAggregate()
{
}
virtual Object getItem(int index)
{
return object[index];
}
virtual MyIterator* CreateIterator()
{
return new ConcreteAggrete(this);
}
virtual int getSize()
{
return SIZE;
}
private:
Object object[SIZE];
};
int main(void)
{
//創建一個集合
Aggregate *ag = new ConcreteAggrete();
//創建一個遍歷這個集合的迭代器
MyIterator *it = ag->CreateIterator();
//通過迭代器 遍歷 集合
for(;!(it->IsDone());it->Next())
{
cout << it->CurrentItem() << " ";
}
delete it;
delete age;
return 0;
}