设计模式之迭代器模式

前言

"数据结构" 模式。常常有一些组件在内部具有特定的数据结构,如果让客户程序依赖这些特定的数据结构,将极大的破坏组件的复用。这时候,将这些特定的数据结构封装在内部,在外部提供统一的接口,来实现与特定数据结构无关的访问,是一种行之有效的解决方案

定义

提供一种方法顺序访问一个聚合对象中的各个元素,而且不暴露(稳定)该对象的内部表示

动机

在软件构建过程中,集合对象内部结构常常变化各异。但对于这些集合对象,我们希望在不暴露其内部结构的同时,可以让外部客户代码透明的访问其中包含的元素;同时这种 "透明遍历" 也为 "同一种算法在多种集合对象上进行操作" 提供了可能

使用面向对象技术将这种遍历机制抽象为 "迭代器对象" 为 "应对变化中的集合对象" 提供了一种优雅的方式

案例

代码------抽象版本(性能损耗)

cpp 复制代码
template<typename T>
class Iterator
{
public:
    virtual void first() = 0;
    virtual void next() = 0;
    virtual bool isDone() const = 0;
    virtual T& current() = 0;
};



template<typename T>
class MyCollection{
    
public:
    
    Iterator<T> GetIterator(){
        //...
    }
    
};

template<typename T>
class CollectionIterator : public Iterator<T>{
    MyCollection<T> mc;
public:  
    CollectionIterator(const MyCollection<T> & c): mc(c){ }
    
    void first() override {
        
    }
    void next() override {
        
    }
    bool isDone() const override{
        
    }
    T& current() override{
        
    }
};

void MyAlgorithm()
{
    MyCollection<int> mc;
    
    Iterator<int> iter= mc.GetIterator();
    
    for (iter.first(); !iter.isDone(); iter.next()){
        cout << iter.current() << endl;
    }
}

代码------模板版本(推荐)

cpp 复制代码
#include <iostream>

template <typename T>
class MyIterator {
public:
    MyIterator(T* ptr) : m_ptr(ptr) {}
    T& operator*() const { return *m_ptr; }
    MyIterator& operator++() { m_ptr++; return *this; }
    bool operator!=(const MyIterator& other) const { return m_ptr!= other.m_ptr; }

private:
    T* m_ptr;
};

template <typename T>
class MyContainer {
public:
    MyContainer(T* arr, int size) : m_arr(arr), m_size(size) {}
    MyIterator<T> begin() { return MyIterator<T>(m_arr); }
    MyIterator<T> end() { return MyIterator<T>(m_arr + m_size); }

private:
    T* m_arr;
    int m_size;
};

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    MyContainer<int> container(arr, 5);
    for (auto it = container.begin(); it!= container.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    return 0;
}

类图

总结

迭代抽象:访问一个聚合对象的内容而无需暴露它的内部表示

迭代多态:为遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作

迭代器的健壮性考虑:遍历的同时更改迭代器所在的集合结构,会导致问题

相关推荐
Lucis__1 小时前
再探类&对象——C++入门进阶
开发语言·c++
北京不会遇到西雅图2 小时前
【SLAM】【后端优化】不同优化方法对比
c++·机器人
jndingxin2 小时前
c++多线程(6)------ 条件变量
开发语言·c++
程序员莫小特2 小时前
老题新解|大整数加法
数据结构·c++·算法
洲覆4 小时前
C++ 模板、泛型与 auto 关键字
开发语言·数据结构·c++
千里马-horse5 小时前
Async++ 源码分析7--parallel_reduce.h
开发语言·c++·async++·parallel_reduce
江公望5 小时前
Qt QThread使用方法入门浅解
c++·qt
叫我龙翔5 小时前
【MySQL】从零开始了解数据库开发 --- 数据表的约束
android·c++·mysql·数据库开发
Yupureki5 小时前
从零开始的C++学习生活 6:string的入门使用
c语言·c++·学习·visual studio
Madison-No75 小时前
【C++】探秘string的底层实现
开发语言·c++