迭代器模式
一、迭代器模式的概念
迭代器模式屬於行爲型模式,用於順序訪問集合對象的元素,不需要知道集合對象的底層表示。
二、迭代器模式使用場景
1、訪問一個聚合對象的內容而無須暴露它的內部表示。
2、需要爲聚合對象提供多種遍歷方式。
3、爲遍歷不同的聚合結構提供一個統一的接口。
三、迭代器模式構建方法
1、迭代器抽象類(Iterator)
迭代器抽象類定義了訪問和遍歷元素的接口,聲明瞭用於遍歷數據元素的方法,是迭代器具體實現類的父類。
2、迭代器具體實現類(ConcreteIterator)
迭代器具體實現類用於實現迭代器抽象類中定義的接口和方法。
3、容器抽象類(Aggregate)
容器抽象類用於存儲和管理元素對象,聲明一個用於創建一個迭代器對象的方法,充當抽象迭代器工廠角色。
4、容器具體實現類(concreteAggregate)
容器具體實現類用於實現容器抽象類中定義的接口和方法
四、迭代器模式的示例
// IteratorPattern.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//
#include <iostream>
#include <string>
#include <vector>
#define DELETE_PTR(p) {if(p!=nullptr){delete (p); (p)=nullptr;}}
using namespace std;
class MyIterator
{
public:
virtual void first() = 0;
virtual void next() = 0;
virtual int currentItem() = 0;
virtual bool isEnd() = 0;
};
class Aggregate
{
public:
virtual void addItem(int num) = 0;
virtual int getItem(int index) = 0;
virtual MyIterator *createIterator() = 0;
virtual int getSize() = 0;
};
class ConcreteIterator : public MyIterator
{
public:
ConcreteIterator(Aggregate *pAggregate)
{
m_pAggregate = pAggregate;
m_index = 0;
}
~ConcreteIterator()
{
DELETE_PTR(m_pAggregate);
m_index = 0;
}
void first()
{
m_index = 0;
}
void next()
{
if (m_index < m_pAggregate->getSize())
{
m_index++;
}
}
int currentItem()
{
return m_pAggregate->getItem(m_index);
}
bool isEnd()
{
if (m_index == m_pAggregate->getSize())
{
return true;
}
return false;
}
private:
int m_index;
Aggregate *m_pAggregate;
};
class ConcreteAggregate : public Aggregate
{
public:
ConcreteAggregate()
{
m_elemVec.clear();
}
~ConcreteAggregate()
{
if (!m_elemVec.empty())
{
vector<int> tmpVec;
m_elemVec.swap(tmpVec);// 釋放內存
m_elemVec.clear();
}
}
void addItem(int num)
{
cout << "迭代器中添加元素: " << num << endl;
m_elemVec.push_back(num);
}
int getItem(int index)
{
if (index < m_elemVec.size())
{
return m_elemVec.at(index);
}
return -1;
}
{
return new ConcreteIterator(this);
}
int getSize()
{
return m_elemVec.size();
}
private:
vector<int> m_elemVec;;
};
int main()
{
cout << "--------------------迭代器模式--------------------" << endl;
Aggregate *pAggregate = dynamic_cast<Aggregate*>(new ConcreteAggregate);
pAggregate->addItem(1);
pAggregate->addItem(2);
pAggregate->addItem(3);
pAggregate->addItem(4);
pAggregate->addItem(5);
pAggregate->addItem(6);
pAggregate->addItem(7);
pAggregate->addItem(8);
pAggregate->addItem(9);
pAggregate->addItem(10);
MyIterator *myIter = pAggregate->createIterator();
cout << "----------------打印出所有的元素------------------" << endl;
while (!myIter->isEnd())
{
cout << myIter->currentItem() << " ";
myIter->next();
}
cout << endl;
DELETE_PTR(pAggregate);
DELETE_PTR(myIter);
std::cout << "Hello World!\n";
getchar();
}
運行結果:
五、迭代器模式的優缺點
優點:
1、它支持以不同的方式遍歷一個聚合對象,在同一個聚合上可以有多個遍歷。
2、迭代器簡化了聚合類,迭代器的引入,不需要在原有聚合對象中提供遍歷數據的方法。
3、增加新的聚合類和迭代器類都很方便,無須修改原有代碼,符合“開閉原則”。
缺點:
1、增加了系統的複雜性,迭代器模式將存儲數據和遍歷數據的職責分離,增加新的聚合類需要對應增加新的迭代器類,類的個數會成對增加。
2、抽象迭代器的設計難度較大,需要充分考慮到系統將來的擴展性。
能力有限,如有錯誤,多多指教。。。