Iterator 패턴
Iterator 패턴이란, 무엇인가 많이 모여있는 것들을 순서대로 지정하면서 전체를 검색하는 처리를 실행하기 위한 것이다. iterator는 무엇인가를 ‘반복한다’ 라는 의미이며, 반복자라고도 한다.
Aggregate 인터페이스
Aggregate 인터페이스는 요소들이 나열되어 있는 ‘집합체’를 나타낸다. 이 인터페이스를 구현하고 있는 클래스는 배열과 같은 무엇인가가 많이 모여 있다.
public interface Aggregate {
public abstract Iterator iterator();
}
Iterator 인터페이스
Iterator 인터페이스는 요소를 하나씩 나열하면서 루프 변수와 같은 역할을 수행한다.
‘다음 요소’ 가 존재하는지를 조사하기 위한 boolean형 hasNext 메소드
‘다음 요소’ 를 얻기 위한 Object형 next 메소드
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
Book 클래스
- 문자열을 저장하는 name
- 문자열을 받는 생성자
- 책 이름을 반환하는 getName 메소드
public class Book {
private String name;
public Book(String name){
this.name = name;
}
public String getName(){
return name;
}
}
BookShelf 클래스
Aggregate 인터페이스를 구현
public class BookShelf implements Aggregate {
private Book[] books;
private int last = 0;
public BookShelf(int maxsize){
this.books = new Book[maxsize];
}
public Book getBookAt(int index){
return books[index];
}
public void appendBook(Book book){
this.books[last] = book;
last++;
}
public int getLength(){
return last;
}
public Iterator iterator(){
return new BookShelfIterator(this);
}
}
BookShelfIterator 클래스
public class BookShelfIterator implements Iterator{
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf){
this.bookShelf = bookShelf;
this.index = 0;
}
public boolean hasNext(){
if(index < bookShelf.getLength()){
return true;
}
else{
return false;
}
}
public Object next(){
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
Main 클래스
public class Main {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(4); // index = 4
bookShelf.appendBook(new Book("Around the World in 80 Days"));
bookShelf.appendBook(new Book("Bible"));
bookShelf.appendBook(new Book("Cinderella"));
bookShelf.appendBook(new Book("Daddy-Long-Legs"));
Iterator it = bookShelf.iterator();
/*
* while 루프가 돌아가고, 루프 내에서 it.next()에 의해
* 책을 한 권씩 조사하게 된다.
*/
while(it.hasNext()){
Book book = (Book)it.next();
System.out.println(book.getName());
}
}
}
Iterator 패턴의 등장인물
Iterator(반복자)의 역할 : 요소를 순서대로 검색해가는 인터페이스(API)를 결정
ConcreteIterator(구체적인 반복자)의 역할 : Iterator가 결정한 인터페이스(API)를 실제로 구현
Aggregate(집합체)의 역할 : Iterator 역할을 만들어내는 인터페이스(API)를 결정
ConcreteAggregate(구체적인 집합체)의 역할 : Aggregate 역할이 결정한 인터페이스(API)를 실제로 구현하는 일




