聊城網(wǎng)站建設(shè)上饒seo博客
1、迭代器模式的提出
在軟件開發(fā)過程中,操作的集合對象內(nèi)部結(jié)構(gòu)常常變化,在訪問這些對象元素的同時(shí),也要保證對象內(nèi)部的封裝性。迭代器模式提供了一種利用面向?qū)ο蟮谋闅v方法來遍歷對象元素。迭代器模式通過抽象一個(gè)迭代器類,不同的對象繼承自迭代器類,外部通過統(tǒng)一接口訪問元素。
2、需求描述
設(shè)計(jì)一個(gè)能添加數(shù)據(jù)元素的容器類,并且能夠遍歷容器數(shù)據(jù)元素。
3、功能實(shí)現(xiàn)
(1)UML圖如下:
?
(2)代碼實(shí)現(xiàn)如下:
#include <iostream>
#include <vector>// 抽象迭代器接口
template<typename T>
class Iterator {
public:virtual T& operator*() = 0;virtual Iterator<T>& operator++() = 0;virtual bool operator!=(const Iterator<T>& other) const = 0;virtual ~Iterator(){};
};// 具體迭代器類
template<typename T>
class ConcreteIterator : public Iterator<T> {
public:ConcreteIterator(T* ptr) : m_ptr(ptr) {}T& operator*() override {return *m_ptr;}Iterator<T>& operator++() override {++m_ptr;return *this;}bool operator!=(const Iterator<T>& other) const override {const ConcreteIterator* concreteOther = dynamic_cast<const ConcreteIterator*>(&other);return m_ptr != concreteOther->m_ptr;}private:T* m_ptr;
};// 具體容器類
template<typename T>
class Container {
public:void add(const T& element) {m_elements.push_back(element);}Iterator<T>* begin() {return new ConcreteIterator<T>(&m_elements[0]);}Iterator<T>* end() {return new ConcreteIterator<T>(&m_elements[m_elements.size()]);}
private:std::vector<T> m_elements;
};class Client
{
public:void doWork(){Container<float> container;container.add(1.0);container.add(2.0);container.add(3.2);Iterator<float>* itBegin = container.begin();Iterator<float>* itEnd = container.end();while (*itBegin != *itEnd) {std::cout << **itBegin << "\n";++(*itBegin);}delete itBegin;delete itEnd;itBegin = nullptr;itEnd = nullptr;}
};int main() {Client obj;obj.doWork();return 0;
}
程序運(yùn)行結(jié)果如下:
?根據(jù)容器下標(biāo)實(shí)現(xiàn)的迭代器模式方法也可參考:設(shè)計(jì)模式-迭代器模式 C++實(shí)現(xiàn)_c++ 迭代器模式_MachineChen的博客-CSDN博客
4、面向?qū)ο髮?shí)現(xiàn)迭代器分析
面向?qū)ο髮?shí)現(xiàn)的迭代器模式是在程序運(yùn)行時(shí),通過虛函數(shù)去操作對象元素;相比于C++中的泛型編程實(shí)現(xiàn)迭代器的運(yùn)行性能較低(泛型編程是在編譯時(shí)已確定訪問的元素),所以建議使用泛型編程實(shí)現(xiàn)迭代器。
5、泛型編程實(shí)現(xiàn)迭代器
#include <iostream>
#include <vector>template<typename T>
class Iterator {
public:Iterator(T* ptr) : m_ptr(ptr) {}// 解引用操作符T& operator*() {return *m_ptr;}// 前綴自增操作符Iterator& operator++() {++m_ptr;return *this;}// 后綴自增操作符Iterator operator++(int) {Iterator iterator = *this;++m_ptr;return iterator;}// 比較操作符bool operator!=(const Iterator& other) const {return m_ptr != other.m_ptr;}private:T* m_ptr;
};template<typename T>
class Container {
public:void add(const T& element) {m_elements.push_back(element);}Iterator<T> begin() {return Iterator<T>(&m_elements[0]);}Iterator<T> end() {return Iterator<T>(&m_elements[m_elements.size()]);}private:std::vector<T> m_elements;
};class Client
{
public:void doWork(){Container<float> container;container.add(1.0);container.add(2.0);container.add(3.2);for (Iterator<float> it = container.begin(); it != container.end(); ++it) {std::cout << *it << "\n";}}
};int main() {Client obj;obj.doWork();return 0;
}
程序運(yùn)行結(jié)果如下: