Iterator패턴

Design Pattern 2008. 9. 20. 23:58


Iterator패턴이란, 무엇인가 많이 모여있는 것들을 순서대로 지정하면서 전체를 검색하는 처리를 실행하기 위한 것이다.


1.Aggregate인터페이스

package Iterator.Sample;

public interface Aggregate {
    public abstract Iterator iterator();
}

인터페이스에 선언되어 있는 메소드 iterator 메소드 하나뿐이다. 이 메소드는 집합체에 대응하는 Iterator를 1개 작성하기 위한 것이다
iterator메소드를 사용해서 Iterator인터페이스를 구현한 클래스의 인스턴스를 1개 만든다.

2.Iterator인터페이스

package Iterator.Sample;

public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

다음요소가 존재하는지 여부를 위한 hasNext, 존재하면 true반환
다음요소를 얻기위한 next 메소드.. Object타입으로 알 수 있듯 집합체의 요소 1개를 반환.. 또한, 다음 요소를 반환하도록 내부 상태를 다음으로 진행시켜두는 역할을 한다. 여기서는 메소드 이름만.. 구현은 BookShelfIterator

3.Book클래스

package Iterator.Sample;

public class Book {
    private String name;
    public Book(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

책이름 얻기 getName
책이름은 생성자에서 객체를 초기화할 때 인수로 지정한다.

4.BookShelf클래스

package Iterator.Sample;

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);
    }
}

서가를 나타내는 클래스.. 이 클래스를 집합체로 다루기 이해 Aggregate를 구현하고 있다.
iterator메소드는 BookShelf클래스에 대응하는 이터레이터로서, BookShelfIterator라는 클래스의 인스턴스를 생성해서 그것을 반환한다. 이 서가의 책을 나열하고 싶을때 iterator메소드를 호출한다.

5.BookShelf클래스

package Iterator.Sample;

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;
    }
}

Iterator인터페이스를 구현하고있다.
index는 현재 주목하고 있는 책을 가리킨다.
생성자에서 전달된 BookShelf의 인스턴스를 bookshelf에 저장하고 index를 0으로 한다.
hasNext는 index가 책의 권수 bookShelf.length()값보다 작은지 ,큰지로 판정
next메소드는 현재 처리하고 있는 책을Book의 객체 반환하고, 다시 다음으로 진행시키기 위한 메소드.
우선 반환값으로 반환해야 할 책을 book라는 변수로 저장하고 index를 다음으로 진행시킨다.
6.Main클래스

package Iterator.Sample;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("Zround 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());
        }
    }
}


bookShelf.iterator()에 의해 얻어지는 it가 서가를 검색하기 위한 이터레이터의 인스턴스이다.

AND

치킨

Egoist story 2008. 9. 19. 00:47

오늘도 치킨을 먹었습니다. 월요일에도 먹었었는데...

새로 치킨집이 생겼더군요.. Boor치킨..
값도 싸고 메뉴도 다양합니다. 후라이드,간장,양념
7천~8천원입니다.

종전에 먹던 것은 치킨신드롬.. 영계라고 하나..
닭날개랑 봉으로만 이루어져 있고 양념이 아주 맛있습니다. 깔끔하죠..
값은 14000원...

뭐,, 결론은 그렇습니다.
배가 무지고프고 밥이랑 같이 먹어야 겠다.... - 치킨신드롬
치킨은 먹고 싶은데 돈이 없다... - 부어치킨(반마리도 되네요..4200원인가...)


당분간은 부어치킨을 많이 먹을 것 같네요 ^^

사용자 삽입 이미지
AND





뻘글이라도 하루에 하나씩 포스팅 하겠다





AND