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
'프로그래밍 > GoF' 카테고리의 다른 글
[행동 패턴] - 감시자(Observer) (0) | 2022.01.08 |
---|---|
[행동 패턴] - 메멘토(Memento) (0) | 2022.01.08 |
[행동 패턴] - 해석자(Interpreter) (0) | 2022.01.06 |
[행동 패턴] - 명령(Command) (0) | 2022.01.05 |
[행동 패턴] - 책임 연쇄(Chain of responsibility) (0) | 2022.01.05 |