设计模式之迭代器模式

前言

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

定义

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

动机

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

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

案例

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

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

类图

总结

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

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

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

相关推荐
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
willow2 天前
Axios由浅入深
设计模式·axios
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
七月丶4 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞4 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼4 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟5 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder5 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++