public interface Aggregate { public abstract Iterator iterator(); }
=================================================
//Iterator interface
public interface Iterator { public abstract boolean hasNext(); public abstract Object next(); }
=================================================
//BookShelf class
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; } @Override public Iterator iterator() { // TODO Auto-generated method stub return new BookShelfIterator(this); }
}
=================================================
//BookShelfIterator class
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; } }
=================================================
//Book class
public class Book { private String name; public Book(String name){ this.name = name; } public String getName(){ return name; } }
=================================================
//Main class
public class Main {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BookShelf bookShelf = new BookShelf(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.hasNext()){ Book book = (Book)it.next(); System.out.println(book.getName()); } }
}
와 같습니다.
이렇게 하면 실행 결과는
Around the world in 80 Days Bible Cinderella Daddy-Long-Legs
와 같이 나옵니다.
그렇다면 그냥 for 문을 돌리면 될 것을 복잡하게 이런 패턴을 왜 쓰는가
하면 그냥 for 문을 쓰는 것 보다 iterator 를 쓰면 구현 부분에 독립적이
되기 때문입니다.
Book 배열에서 Vector 나 ArrayList 같은 Collection 으로 바꾼다 하더라도
while(it.hasNext()){ Book book = (Book)it.next(); System.out.println(book.getName()); }
댓글