반복자 패턴
이터레이터(iterator)를 사용하여 컬렉션(collection)의 요소에 접근하는 디자인 패턴으로, 객체를 저장하는 방식은 보여주지 않으면서도 클라이언트가 객체들에게 일일이 접근할 수 있게 해주는 방법
행위 패턴
Iterator 인터페이스
는 컬렉션 순회에 필요한 작업을 선언Iterator의 구현체 (ArrayIterator)
는 컬렉션 순회를 위한 알고리즘 구현컬렉션 인터페이스 (Aggregator)
는 컬렉션과 호환되는 반복자를 얻기 위해 하나 이상의 메소드를 선언컬렉션 인터페이스의 구현체 (Array)
는 클라이언트가 요청할 때마다 특정 구현체 클래스의 새로운 인스턴스를 반환public interface Aggregator {
Iterator iterator();
}
public interface Iterator {
boolean next();
Object current();
// next()
// Iterator 인터페이스를 통해서 Aggregator의 다음 구성 데이터를 얻을 수 있도록 하고,
// 얻을 수 있다면 true를 반환, 더 이상 얻을 수 없다면 false를 반환
// current()
// 구성 데이터를 하나 얻어 반환하는데, 이때 구성 데이터에 대한 타입은 정해지지 않아야 하므로 Object 타입으로 반환
}
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 + ")";
}
}
public class Array implements Aggregator {
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);
}
}
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);
}
}
public static void main(String[] args) {
Item[] items = {
new Item("CPU", 1000),
new Item("Keyboard", 2000),
new Item("Mouse", 3000),
new Item("HDD", 50)
};
Array array = new Array(items);
Iterator it = array.iterator();
while (it.next()) {
Item item = (Item)it.current();
System.out.println(item);
}
}
}
/*
(CPU, 1000)
(Keyboard, 2000)
(Mouse, 3000)
(HDD, 50)
*/