👣 문제 상황
자료들을 담고 있는 컨테이너들을 순회하는 방법을
자료구조에 상관없이
공통 인터페이스로 추상화해서 사용하는 패턴.
👣 해결 방법
interface Aggregate {
Iterator createIterator();
}
interface Iterator {
boolean hasNext();
Object next();
}
class ConcreteAggregate implements Aggregate {
private String[] elements;
public ConcreteAggregate() {
elements = new String[]{"A", "B", "C", "D", "E"};
}
@Override
public Iterator createIterator() {
return new ConcreteIterator(elements);
}
}
class ConcreteIterator implements Iterator {
private String[] elements;
private int position;
public ConcreteIterator(String[] elements) {
this.elements = elements;
position = 0;
}
@Override
public boolean hasNext() {
return position < elements.length;
}
@Override
public Object next() {
if (hasNext()) {
String element = elements[position];
position++;
return element;
}
return null;
}
}
public class Main {
public static void main(String[] args) {
Aggregate aggregate = new ConcreteAggregate();
Iterator iterator = aggregate.createIterator();
while (iterator.hasNext()) {
String element = (String) iterator.next();
System.out.println("Element: " + element);
}
}
}
'디자인 패턴' 카테고리의 다른 글
Programming Paradigm (0) | 2023.07.19 |
---|---|
MVC Pattern - 아키텍쳐 (0) | 2023.07.19 |
Proxy Pattern - 구조 (0) | 2023.07.19 |
Observer Pattern - 행위 (0) | 2023.07.19 |
Strategy Pattern - 행위 (0) | 2023.07.19 |