(三)行为模式: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。通过实现这些接口和类,我们可以创建一个包含整数元素的集合对象,并使用迭代器遍历集合中的元素。

相关推荐
七月丶12 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞12 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼13 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
端平入洛3 天前
delete又未完全delete
c++