Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ch.1 Iterator Pattern <<interface>> Aggregate +iterator

Similar presentations


Presentation on theme: "Ch.1 Iterator Pattern <<interface>> Aggregate +iterator"— Presentation transcript:

1 Ch.1 Iterator Pattern <<interface>> Aggregate +iterator
+hasNext +next Creates ▶ BookShelf -books[] -last +getbookAt +appendBook +getLength +iterator BookShelfIterator -bookShelf -index +hasNext +next - 배열 books의 내용을 모두 print out 하는 일반적인 방법 for (I = 0; I < books.length; i++) System.out.println(books[I]); 반복의 대상이 배열이 아닌 queue, stack, 혹은 vector 이면 code의 일부분이 수정되어야 함. 반복의 대상이 바뀌더라도 항상 같은 방법으로 반복하도록 하는 패턴 Book -name +getName 장 덕 성 계명대학교 컴퓨터공학과 정보공학실험실

2 Ch.1 Iterator Pattern public class Book { private String name = "";
▌Book Class public class Book { private String name = ""; public Book(String name) { this.name = name; } public String getName() { return name; 장 덕 성 계명대학교 컴퓨터공학과 정보공학실험실

3 Ch.1 Iterator Pattern ▌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; public Iterator iterator() { return new BookShelfIterator(this); Iterator() 메소드는 BookShelfIterator에 대한 instance를 만듬 BookShelfIterator에는 hasNext()와 next()가 존재 장 덕 성 계명대학교 컴퓨터공학과 정보공학실험실

4 Ch.1 Iterator Pattern ▌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; hasNext()는 다음 요소가 있는가를 검사 next()는 다음 요소를 지적하기 위해 index를 증가 장 덕 성 계명대학교 컴퓨터공학과 정보공학실험실

5 public static void main(String[] args) {
Ch.1 Iterator Pattern ▌Main Class public class Main { public static void main(String[] args) { 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()); } iterator()의 반환값은 BookShelfIterator에 대한 instance, 이것을 상위의 iterator class type인 it에 저장. while 문에서 hasNext()와 next()를 사용하고 있음. 역방향으로 진행하는 reverse_iterator()를 정의할 수 있음. 특정위치로 jump 하는 jump_iterator()도 정의 가능. java.util.Iterator class를 import 해서 특정 class 내의 요소를 반복적 으로 선택할 수 있음. 장 덕 성 계명대학교 컴퓨터공학과 정보공학실험실


Download ppt "Ch.1 Iterator Pattern <<interface>> Aggregate +iterator"

Similar presentations


Ads by Google