Aggregator의 종류에 상관없이 데이터를 하나씩 가져올 수 있는 패턴을 의미
Class Diagram : 클래스 간의 관계를 나타낸 다이어그램.
UML 에서 정의한 다이어그램 중 하나
Aggregator(interface)
Iterator(interface)
Array(class)
ArrayInterator(class)
Item(class)
public interface Iterator {
/// Aggregator의 다음 구성 데이터를 얻을 수 있음
/// 다음 구성이 얻을 수 있으면 true
/// 얻을 수 없으면 false
boolean next();
/// 구성 데이터를 받아 리턴함.
Object current();
}
// Aggregator가 Iterator를 생성한다.
public interface Aggregator {
Iterator iterator();
}
public class Item {
private String name;
private int cost;
public Item(String name, int cost){
this.name = name;
this.cost = cost;
}
@Override
public String toString(){
return "("+name+", "+cost+")";
}
}
// Aggregator의 메소드를 Array에서 구현한다.
public class Array implements Aggregator{
// Array가 Item을 필드로써 가진다.
// Array가 Item를 여러개 가질수 있다.
private Item[] items;
public Array(Item[] items){
this.items = items;
}
public Item getItem(int index){
return items[index];
}
public int getCount(){
return items.length;
}
@Override
public Iterator iterator() {
return new ArrayIterator(this);
}
}
//Iterator의 메소드를 ArrayInterator에서 구현한다.
public class ArrayIterator implements Iterator {
private Array array;
private int index;
public ArrayIterator(Array array){
this.array = array;
this.index = -1; // 현재 가르키는 구성 데이터의 인덱스
}
@Override
public boolean next() {
index++;
return index < array.getCount();
}
@Override
public Object current() {
return array.getItem(index);
}
}
//import java.lang.reflect.Array;
//import java.util.*;
// 기존 패키지를 사용하면 같은 이름으로 충돌
public class Main {
public static void main(String[] args) {
Item[] items = {
new Item("CPU", 1000),
new Item("Keyboard", 1000),
new Item("Mouse", 1000),
new Item("HDD", 1000),
};
Array array = new Array(items);
Iterator it = array.iterator();
while (it.next()){
Item item = (Item)it.current();
System.out.println(item);
}
}
}
// 결과
(CPU, 1000)
(Keyboard, 1000)
(Mouse, 1000)
(HDD, 1000)