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

目录

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++实现迭代器模式的实例


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

猜你喜欢

转载自blog.csdn.net/bigger_belief/article/details/132334307