设计模式之迭代器模式

前言

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

定义

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

动机

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

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

案例

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

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;
}

类图

总结

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

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

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

相关推荐
好好学习啊天天向上8 分钟前
多维c++ vector, vector<pair<int,int>>, vector<vector<pair<int,int>>>示例
开发语言·c++·算法
我狸才不是赔钱货13 分钟前
CUDA:通往大规模并行计算的桥梁
c++·人工智能·pytorch
winds~41 分钟前
【GUI】本地电脑弹出远程服务器的软件GUI界面
运维·服务器·c++
成钰1 小时前
设计模式之抽象工厂模式:最复杂的工厂模式变种
java·设计模式·抽象工厂模式
Asort2 小时前
JavaScript设计模式(二十三)——访问者模式:优雅地扩展对象结构
前端·javascript·设计模式
xiaoye37083 小时前
23种设计模式之策略模式
设计模式·策略模式
杨筱毅3 小时前
【穿越Effective C++】条款8:别让异常逃离析构函数——C++异常安全的关键支柱
c++·effective c++
code monkey.3 小时前
【探寻C++之旅】C++ 智能指针完全指南:从原理到实战,彻底告别内存泄漏
c++·c++11·智能指针
数据知道4 小时前
Go语言设计模式:建造者模式详解
设计模式·golang·建造者模式
崎岖Qiu4 小时前
【设计模式笔记11】:简单工厂模式优缺分析
java·笔记·设计模式·简单工厂模式