(三)行为模式:4、迭代器模式(Iterator Pattern)(C++示例)

目录

[1、迭代器模式(Iterator Pattern)含义](#1、迭代器模式(Iterator Pattern)含义)

2、迭代器模式的UML图学习

3、迭代器模式的应用场景

4、迭代器模式的优缺点

(1)优点

(2)缺点

5、C++实现迭代器模式的实例


1、迭代器模式(Iterator Pattern)含义

迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中各个元素,而不暴露该对象的内部表示。【DP】

通过使用迭代器模式,可以将遍历算法与集合对象解耦,使得集合对象的结构和遍历算法可以独立变化。

2、迭代器模式的UML图学习

迭代器模式的主要几个角色:

(1)迭代器(Iterator):定义了访问和遍历集合对象元素的接口,包括获取下一个元素、判断是否还有元素等方法。

(2)具体迭代器(Concrete Iterator):实现迭代器接口,对具体的集合对象进行遍历操作。

(3)集合(Aggregate):定义创建迭代器对象的接口,可以是一个抽象类或接口。

(4)具体集合(Concrete Aggregate):实现集合接口,创建相应的具体迭代器对象。

3、迭代器模式的应用场景

(1)需要遍历一个聚合对象,而又不暴露其内部表示。

(2)需要对聚合对象提供多种遍历方式。

(3)需要提供一个统一的遍历接口,以便客户端代码能够以统一的方式处理不同类型的集合对象。

4、迭代器模式的优缺点

(1)优点

1)简化集合对象的接口:迭代器模式将遍历集合对象的责任封装到迭代器中,使得集合对象本身的接口更加简洁。

2)支持多种遍历方式:通过定义不同的迭代器,可以支持不同的遍历方式,如正向遍历、逆向遍历等。

3)提供了一种统一的遍历接口:迭代器模式提供了一种统一的遍历接口,使得客户端代码可以以统一的方式访问不同类型的集合对象。

(2)缺点

1)增加了系统的复杂性:引入迭代器模式会增加额外的类和接口,增加了系统的复杂性。

2)遍历过程中不能修改集合对象:使用迭代器遍历集合对象时,不能在遍历过程中修改集合对象,否则可能导致遍历结果不准确。

5、C++实现迭代器模式的实例

cpp 复制代码
#include <iostream>
#include <vector>

// 迭代器接口
class Iterator 
{
public:
    virtual int next() = 0;
    virtual bool hasNext() = 0;
};

// 具体迭代器
class ConcreteIterator : public Iterator 
{
private:
    std::vector<int> collection;
    int position;

public:
    ConcreteIterator(std::vector<int> coll) : collection(coll), position(0) {}

    int next() override 
    {
        return collection[position++];
    }

    bool hasNext() override 
    {
        return position < collection.size();
    }
};

// 集合接口
class Aggregate 
{
public:
    virtual Iterator* createIterator() = 0;
};

// 具体集合
class ConcreteAggregate : public Aggregate 
{
private:
    std::vector<int> collection;

public:
    ConcreteAggregate(std::vector<int> coll) : collection(coll) {}

    Iterator* createIterator() override 
    {
        return new ConcreteIterator(collection);
    }
};

int main() 
{
    std::vector<int> data = {1, 2, 3, 4, 5};
    Aggregate* aggregate = new ConcreteAggregate(data);
    Iterator* iterator = aggregate->createIterator();

    while (iterator->hasNext()) 
    {
        std::cout << iterator->next() << " ";
    }
    std::cout << std::endl;

    delete iterator;
    delete aggregate;

    return 0;
}

在上述示例中,我们定义了迭代器接口Iterator和具体迭代器ConcreteIterator,以及集合接口Aggregate和具体集合ConcreteAggregate。通过实现这些接口和类,我们可以创建一个包含整数元素的集合对象,并使用迭代器遍历集合中的元素。

相关推荐
mjhcsp8 小时前
C++ long long 类型深度解析:大整数处理的基石
开发语言·c++·策略模式·long long
Larry_Yanan8 小时前
QML学习笔记(四十五)QML与C++交互:信号槽的双向实现
c++·笔记·qt·学习·ui·交互
冯诺依曼的锦鲤8 小时前
算法练习:双指针专题
c++·算法
WaWaJie_Ngen8 小时前
【设计模式】工厂模式(Factory)
c++·设计模式·简单工厂模式·工厂方法模式·抽象工厂模式
YuanlongWang8 小时前
C# 设计模式——工厂模式
开发语言·设计模式·c#
埃伊蟹黄面8 小时前
深入理解STL关联容器:map/multimap与set/multiset全解析
开发语言·c++
消失的旧时光-19439 小时前
MQTT主题架构的艺术:从字符串拼接走向设计模式
设计模式
「QT(C++)开发工程师」9 小时前
C++语言编程规范-风格
linux·开发语言·c++·qt
CandyU29 小时前
C++ 学习 —— 02 - 排序算法
c++·学习·排序算法
浮灯Foden10 小时前
算法-每日一题(DAY18)多数元素
开发语言·数据结构·c++·算法·leetcode·面试