Java/design pattern Iterator Pattern 우혁이 아빠 2012. 7. 16. 01:09 package com.tistory.tazz009.iterator; public interface Iterator { public boolean hasNext(); public Object next(); } package com.tistory.tazz009.iterator; public interface Aggregate { public Iterator iterator(); } package com.tistory.tazz009.iterator; public class Book { private String name; public Book() { } public Book(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Book [name=" + name + "]"; } } package com.tistory.tazz009.iterator; import java.util.Arrays; public class BookShelf implements Aggregate { private Book[] books; private int last = 0; public BookShelf(int maxsize) { books = new Book[maxsize]; } public void appendBook(Book book) { this.books[last] = book; last++; } public Book getBookAt(int index) { return books[index]; } public int getLength() { return last; } public Iterator iterator() { return new BookShelfIterator(this); } @Override public String toString() { return "BookShelf [books=" + Arrays.toString(books) + "]"; } } package com.tistory.tazz009.iterator; public class BookShelfIterator implements Iterator { private BookShelf bookShelf; private int index; public BookShelfIterator(BookShelf bookShelf) { this.bookShelf = bookShelf; this.index = 0; } @Override public boolean hasNext() { if (index < bookShelf.getLength()) { return true; } else { return false; } } @Override public Object next() { Book book = bookShelf.getBookAt(index); index++; return book; } } @Test public void test001() throws Exception { 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.toString()); } } 저작자표시