Iterator pattern

반복자 패턴은 반복 작업을 캡슐화하는 패턴이다. 개발을 하다보면 자료구조 안에 있는 객체에 일일이 접근해야하는 상황이 있다. 어떻게 저장했느냐에 따라 객체에 접근하는 방식이 다른데, 반복자 패턴은 객체 저장 방식을 숨기면서도 객체에 일일이 접근할 수 있게 해준다.

먼저 반복자 인터페이스를 정의한다.

template <class T>
class Iterator 
{
public:
    virtual bool hasNext();
    virtual T next();
    virtual void remove();
}

그 다음 구상 클래스를 만든다

class ArrayIterator : Iterator<int>
{
    int currentIndex = -1;
    vector<int> myArr;
public:
    ArrayIterator(vector<int> myArr)
    {
        this->myArr = myArr;
    }

    bool hasNext()
    {
        return currentIndex + 1 < myArr.size();
    }

    int next()
    {
        return myArr[++currentIndex];
    }

    void remove()
    {
        myArr.erase(myArr.begin() + currentIndex--);
    }
};

class StackIterator : Iterator<int>
{
    stack<int> myStack;
public:
    StackIterator(stack<int> myStack)
    {
        this->myStack = myStack;
    }

    bool hasNext()
    {
        return !myStack.empty();
    }

    int next()
    {
        int result = myStack.top();
        myStack.pop();
        return result;
    }

    void remove()
    {
        myStack.pop();
    }
};

이렇게 구현하고 나면 저장 방법과 데이터 타입에 구애받지 않고 반복자 패턴으로 개별 요소에 하나씩 접근할 수 있게 된다.

참고