프로그래밍/GoF

[행동 패턴] - 반복자(Iterator)

MAKGA 2022. 1. 6. 23:23
320x100

구조

#pragma once

#include <iostream>
#include <vector>

class IteratorInterface
{
public:
    virtual void first() = 0;
    virtual void next() = 0;
    virtual bool isDone() = 0;
    virtual int currentItem() = 0;
};

class Aggregate
{
public:
    virtual IteratorInterface* createIterator() = 0;
};

class Interator : public IteratorInterface
{
private:
    std::vector<int> state;
    std::size_t index;

public:
    Interator()
    {
        state = { 0, 1, 2 };
    }

    void first()
    {
        index = 0;
    }

    void next() override
    {
        index++;
    }

    bool isDone() override
    {
        return index > state.size();
    }

    int currentItem() override
    {
        return state[index];
    }
};

class Aggregate : public Aggregate
{
public:
    IteratorInterface* createIterator() override
    {
        return new ConcreteInterator();
    }
};

 

사용

int main()
{
    Aggregate aggregate;
    IteratorInterface* iterator = aggregate.createIterator();

    while (!iterator->isDone())
    {
        int item = iterator->currentItem();
        std::cout << item;
        iterator->next();
    }

    system("pause");

    return 0;
}

 

해당 패턴은 Morder C++을 사용한다면 많이 사용할 패턴이다.

컨테이너 대부분이 iterator를 이용한 반복자를 제공한다.

320x100