내부 표현부를 노출하지 않고 어떤 집합 객체에 속한 원소들을 순차적으로 접근할 수 있는
방법을 제공
public class Item {
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Item{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
//Aggregate
public interface Aggregate<T> {
Iterator<T> createIterator();
}
public class ConcreteAggregate implements Aggregate<Item> {
private List<Item> itemList;
public ConcreteAggregate(List<Item> itemList) {
this.itemList = itemList;
}
@Override
public Iterator<Item> createIterator() {
return new ItemIterator(itemList);
}
}
//Iterator
public interface Iterator<E> {
boolean hasNext();
E next();
}
public class ItemIterator implements Iterator<Item> {
private List<Item> itemList;
private int index = 0;
public ItemIterator(List<Item> itemList) {
this.itemList = itemList;
}
@Override
public boolean hasNext() {
return index < itemList.size();
}
@Override
public Item next() {
if (hasNext()) {
return itemList.get(index++);
}
return null;
}
}
public class Main {
public static void main(String[] args) {
Item item1 = new Item("item1", 10000);
Item item2 = new Item("item2", 20000);
Item item3 = new Item("item3", 30000);
List<Item> itemList = new ArrayList<>();
itemList.add(item1);
itemList.add(item2);
itemList.add(item3);
Aggregate<Item> c = new ConcreteAggregate(itemList);
Iterator<Item> myIter = c.createIterator();
while (myIter.hasNext()) {
System.out.println(myIter.next());
}
}
}
Item{name='item1', price=10000}
Item{name='item2', price=20000}
Item{name='item3', price=30000}