设计模式之迭代器模式

前言

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

定义

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

动机

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

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

案例

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

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

类图

总结

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

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

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

相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
weilx12343 天前
C++笔记-文件IO-<fcntl.h>
c++
Smileyqp沛沛3 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·3 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven3 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
程序猿编码3 天前
告别改源码适配模型:纯 C++ 可配置 LLM 推理引擎,全格式全结构兼容
c++·大模型·llm·推理引擎
此生决int3 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++