设计模式之迭代器模式

前言

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

定义

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

动机

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

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

案例

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

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

类图

总结

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

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

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

相关推荐
专注VB编程开发20年1 小时前
IIS Express中可以同时加载并使用.net4.0和.NET 2.0的 DLL
c++·windows·microsoft·c#·vb.net
光头闪亮亮1 小时前
C++凡人修仙法典 - 散修版
c++
程序猿编码4 小时前
基于LLVM的memcpy静态分析工具:设计思路与原理解析(C/C++代码实现)
c语言·c++·静态分析·llvm·llvm ir
猪蹄手4 小时前
C/C++基础详解(三)
开发语言·jvm·c++
再睡一夏就好4 小时前
【排序算法】④堆排序
c语言·数据结构·c++·笔记·算法·排序算法
程序员莫小特4 小时前
老题新解|求一元二次方程
数据结构·c++·算法·青少年编程·c·信息学奥赛一本通
森林古猿14 小时前
论区间dp:常用模型(附极角排序教程)
c++·学习·算法·排序算法·动态规划·几何学
tianchang4 小时前
打造你的本地AI助手:基于RAG+向量数据库的智能问答系统
人工智能·设计模式·node.js
阿巴~阿巴~4 小时前
string 类元素访问方法
开发语言·c++
watson_pillow6 小时前
mfc按钮点击事件没有触发,且程序卡死
c++·mfc