轉載自:
http://patmusing.blog.163.com/blog/static/13583496020101501613155/
“Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.” – GoF
提供一種方法,以順序訪問一個聚合對象中的元素,而又不暴露該聚合對象之內部表示。
An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you want to accomplish. But you probably don’t want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you will need. You might also need to have more than one traversal pending on the same list.
The Iterator pattern lets you do all this. The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object. The Iterator class defines an interface for accessing the list’s elements. An iterator object is responsible for keeping track of the current element; that is, it knows which elements have been traversed already.
在軟件構建過程中, 集合對象內部結構常常變化各異。但對于這些集合對象,我們希望在不暴露其內部結構的同時,可以讓外部客戶代碼透明地訪問其中包含的元素;同時這種“透明遍歷”也為“同一種算法在多種結合對象上進行操作”提供了可能。使用面向對象技術,將這種遍歷機制抽象為“迭代器對象”,為“應對變化中的集合對象”提供了一種優雅的遍歷方式。
Iterator設計模式UML類圖:
要點:
- 迭代抽象: 訪問一個聚合對象的內容,而無需暴露其內部表示。
- 迭代多態: 為遍歷不同的集合結構提供一個統一的接口,從而支持同樣的算法在不同的集合結構上進行操作。
- 迭代器通常不應該修改所在集合的結構,如刪除其中一個元素,也就是迭代器通常是只讀的,但未必盡然。
下面是具體的C++實現代碼:
// Iterator.h
#include <string>
#include <iostream>
#include <memory>
using namespace std;
// 這個類將作為集合中的元素
class Person
{
private:
string name;
string mobilephone;
public:
// 由于ConcreteCollection類的構造函數中的collection = new T[100];這一句,因此,Person類
// 必須提供缺省構造函數
Person()
{
}
Person(const string name, const string mobilephone)
{
this->name = name;
this->mobilephone = mobilephone;
}
~Person()
{
//由于Person類的析構函數會被調用很多次,所以就把下面一行注釋了,以便使得輸出更整潔一些
//cout << "in the destructor of Person..." << endl;
}
public:
// 顯示元素本身的內容
string to_string()
{
string str = name + "\t" + mobilephone;
return str;
}
};
// 這是迭代器所必須實現的接口
template <typename T>
class IIterator
{
public:
virtual T next() = 0; // 取出下一個元素
virtual bool has_next() = 0; // 遍歷完了嗎?如果遍歷完,則返回false;否則,返回true
public:
virtual ~IIterator()
{
cout << "in the destructor of IIterator..." << endl;
}
};
// 定義IIterable接口,所有的欲使用迭代器的集合類,都必須繼承它
template <typename T>
class IIterable
{
public:
virtual auto_ptr<IIterator<T> > get_iterator() = 0; // 獲取迭代器(智能指針)
public:
virtual ~IIterable()
{
cout << "in the destructor of IIterable..." << endl;
}
};
// 具體集合類
template <typename T>
class ConcreteCollection : public IIterable<T>
{
private:
int index;
T *collection;
public:
ConcreteCollection()
{
collection = new T[100];
index = 0;
}
// 增加一個元素
void add_element(T obj)
{
collection[index++] = obj;
}
// 獲取一個指定位置的元素
T get_element_at(int i)
{
return collection[i];
}
// 獲取集合中元素的個數
int get_size()
{
return index;
}
// 獲取迭代器(智能指針)
auto_ptr<IIterator<T> > get_iterator()
{
auto_ptr<IIterator<T> > temp(new ConcreteIterator<Person>(this));
return temp;
}
public:
~ConcreteCollection()
{
delete [] collection; // 對應構造函數中的collection = new T[100];
cout << "in the destructor of ConcreteCollection..." << endl;
}
};
// 具體迭代器類
template <typename T>
class ConcreteIterator : public IIterator<T>
{
private:
int index;
ConcreteCollection<T> *collection;
public:
ConcreteIterator(IIterable<T> *iterable)
{
index = 0;
collection = dynamic_cast<ConcreteCollection<T> *>(iterable);
// 向下轉型,即將基類的指針轉換為派生類的指針,此處使用dynamic_cast
// 是為了進行嚴格的類型檢查。一般而言,向下轉型時不安全的,因此要使
// 用dynamic_cast
}
bool has_next()
{
if(0 == collection->get_size())
{
return false;
}
if(index < collection->get_size())
{
return true;
}
else
{
return false;
}
}
T next()
{
return collection->get_element_at(index++);
}
public:
~ConcreteIterator()
{
cout << "in the destructor of ConcreteIterator..." << endl;
}
};
// Iterator.cpp
#include "Iterator.h"
int main(int argc, char **argv)
{
ConcreteCollection<Person> *collection = new ConcreteCollection<Person>();
collection->add_element(Person("玄機逸士", "13800000001"));
collection->add_element(Person("上官天野", "13800000002"));
collection->add_element(Person("黃藥師 ", "13800000003"));
collection->add_element(Person("歐陽鋒 ", "13800000004"));
collection->add_element(Person("段王爺 ", "13800000005"));
collection->add_element(Person("洪七公 ", "13800000006"));
auto_ptr<IIterator<Person> > iter(collection->get_iterator());
while(iter->has_next())
{
cout << (iter->next()).to_string() << endl;
}
delete collection;
return 0;
}
運行結果:
玄機逸士 13800000001
上官天野 13800000002
黃藥師 13800000003
歐陽鋒 13800000004
段王爺 13800000005
洪七公 13800000006
in the destructor of ConcreteCollection...
in the destructor of IIterable...
in the destructor of ConcreteIterator...
in the destructor of IIterator...
與上述程序對應的UML類圖:
Iterator模式實現需注意的要點:
1. 兩個重要接口,即IIterable和IIterator,它們分別對應的具體類ConcreteCollection和ConcreteIterator。本質上而言ConcreteCollection中存放的是數據,ConcreteIterator中實現的是遍歷的方法。
2. ConcreteCollection中的getIterator()方式的實現技巧。即
return new ConcreteIterator(this);
ConcreteCollection將自己(當然也包括ConcreteCollection中包含的數據)通過ConcreteIterator的構造函數,傳遞給ConcreteIterator,然后ConcreteIterator利用已實現的方法對其進行遍歷。
3. 模板類的應用。上述實現由于使用了模板,因此ConcreteCollection中的元素也可以是除Person類之外的其他類型。