이터레이터 패턴
- 집합 객체 내부 구조를 노출시키지 않으면서 순회하는 방법을 제공하는 패턴
- 리스트, 배열, 트리와 같은 컬렉션 객체 내부의 요소들에 순차적으로 접근할 수 있도록 하는 디자인 패턴
- 다양한 컬렉션에 대해 동일한 방식으로 요소들을 탐색할 수 있는 장점을 지님

주요 구성 요소
1. Iterator
- 요소들을 순차적으로 접근하기 위한 메서드들을 정의하는 인터페이스
- 일반적으로 hasNext()와 next() 메서드가 포함
2. ConcreteIterator
- Iterator 인터페이스를 구현체
- 실제 컬렉션의 요소들을 탐색하는 역할
3. Aggregate
- 컬렉션 객체를 표현하는 인터페이스
- iterator를 생성하는 메서드 createIterator()를 정의
4. ConcreteAggregate
- Aggregate 인터페이스를 구현하여 특정 컬렉션을 나타내며, 이터레이터를 생성
이터레이터 패턴 구현 예시
1. Iterator 인터페이스
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Iterator<T> { | |
boolean hasNext(); | |
T next(); | |
} |
2. ConcreteIterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConcreteIterator<T> implements Iterator<T> { | |
private List<T> collection; | |
private int position = 0; | |
public ConcreteIterator(List<T> collection) { | |
this.collection = collection; | |
} | |
@Override | |
public boolean hasNext() { | |
return position < collection.size(); | |
} | |
@Override | |
public T next() { | |
return collection.get(position++); | |
} | |
} |
3. Aggregate 인터페이스
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Aggregate<T> { | |
Iterator<T> createIterator(); | |
} |
4. ConcreteAggregate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConcreteAggregate<T> implements Aggregate<T> { | |
private List<T> items = new ArrayList<>(); | |
public void addItem(T item) { | |
items.add(item); | |
} | |
public T getItem(int index) { | |
return items.get(index); | |
} | |
public int getSize() { | |
return items.size(); | |
} | |
@Override | |
public Iterator<T> createIterator() { | |
return new ConcreteIterator<>(items); | |
} | |
} |
5. 클라이언트 코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Client { | |
public static void main(String[] args) { | |
ConcreteAggregate<String> aggregate = new ConcreteAggregate<>(); | |
aggregate.addItem("아이템 1"); | |
aggregate.addItem("아이템 2"); | |
aggregate.addItem("아이템 3"); | |
Iterator<String> iterator = aggregate.createIterator(); | |
while (iterator.hasNext()) { | |
String item = iterator.next(); | |
System.out.println(item); | |
} | |
} | |
} |

이터레이터 패턴 장단점
장점
- 이터레이터 패턴은 컬렉션의 순회 방법을 컬렉션 자체와 분리하기 때문에 컬렉션은 요소들을 저장하고 관리하는 역할만 맡으며, 요소들의 순회는 이터레이터 객체가 담당 (SOLID의 SRP 원칙)
- 새로운 순회 방법을 추가할 때 기존의 컬렉션 클래스를 수정할 필요 없이 새로운 이터레이터 클래스를 추가하면 됨 (SOLID의 OCP 원칙)
단점
- 다른 디자인 패턴들과 마찬가지로 클래스가 늘어남에 따라 관리 포인트가 늘어나고 복잡도 증가
실무에서 쓰이는 이터레이터 패턴
1. java.util.Iterator
- 자바 컬렉션 프레임워크에서 이터레이터 패턴을 구현한 대표적인 예
- 컬렉션의 요소들을 순차적으로 접근할 수 있는 방법을 제공
- 앞서 작성한 예제와 동일하게 동작
Iterator 주요 메서드
- hasNext(): 컬렉션에 다음 요소가 있는지 확인합니다. 요소가 있으면 true, 없으면 false를 반환
- next(): 컬렉션의 다음 요소를 반환하며 호출하기 전에 hasNext()를 사용하여 다음 요소가 있는지 확인하는 것이 일반적
- remove(): 선택적 메서드로 현재 이터레이터 위치에서 요소를 제거
- 이 메서드는 반복 중 안전하게 요소를 제거할 수 있도록 지원
- 모든 컬렉션이 해당 메서드를 지원하는 것이 아니기 때문에 호출하기 전 지원 여부 확인 필요
2. 스프링 CompositeIterator
- 여러 개의 이터레이터를 결합하여 하나의 이터레이터로 사용할 수 있게 해주는 클래스
- 이터레이터 패턴의 변형으로 볼 수 있으며, 여러 이터레이터의 요소들을 순차적으로 접근할 수 있도록 지원
- 클라이언트는 여러 컬렉션의 요소들을 단일 이터레이터를 통해 일관되게 순회할 수 있음
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IteratorInSpring { | |
public static void main(String[] args) { | |
List<String> databaseResults = Arrays.asList("DB Record 1", "DB Record 2"); | |
List<String> fileResults = Arrays.asList("File Record 1", "File Record 2", "File Record 3"); | |
List<String> apiResults = Arrays.asList("API Record 1", "API Record 2"); | |
List<Iterator<String>> iterators = new ArrayList<>(); | |
iterators.add(databaseResults.iterator()); | |
iterators.add(fileResults.iterator()); | |
iterators.add(apiResults.iterator()); | |
CompositeIterator<String> compositeIterator = new CompositeIterator<>(); | |
for (Iterator<String> iterator : iterators) { | |
compositeIterator.add(iterator); | |
} | |
while (compositeIterator.hasNext()) { | |
System.out.println(compositeIterator.next()); | |
} | |
} | |
} |

참고
코딩으로 학습하는 GoF의 디자인 패턴 - 백기선 강사님
반응형
'Design Pattern' 카테고리의 다른 글
[디자인 패턴] 메멘토 패턴 (Memento Pattern) (1) | 2024.06.30 |
---|---|
[디자인 패턴] 커맨드 패턴 (Command Pattern) (0) | 2024.06.30 |
[디자인 패턴] 인터프리터 패턴 (Interpreter Pattern) (0) | 2024.06.30 |
[디자인 패턴] 중재자 패턴 (Mediator Pattern) (0) | 2024.06.30 |
[디자인 패턴] 책임 연쇄 패턴 (Chain-of-Responsibility Pattern) (0) | 2024.06.29 |