til

Day4

paulaner80 2021. 12. 22. 12:00
반응형

day3 빼먹음

 

 

1. iterator 패턴

 

 

 

1.

public class IteratorTest {

    public static void main(String[] args) {
        System.out.println("iterator 패턴");

        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("Around the World in 80"));
        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());
        }

    }
}

interface Aggregate{
    abstract Iterator iterator();
}

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

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

class BookShelf implements Aggregate{
    private Book[] books;
    private int last = 0;

    BookShelf(int maxSize){
        this.books = new Book[maxSize];
    }

    Book getBookAt(int index){
        return books[index];
    }

    void appendBook(Book book){
        this.books[this.last] = book;
        this.last ++;
    }

    int getLength(){
        return last;
    }

    @Override
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}

class BookShelfIterator implements Iterator{
    private BookShelf bookShelf;
    private int index;

    BookShelfIterator(BookShelf bookShelf){
        this.bookShelf = bookShelf;
        this.index = 0;
    }


    @Override
    public boolean hasNext() {
        if(index < this.bookShelf.getLength()){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Object next() {
        Book book = bookShelf.getBookAt(index);
        index++;
        return book;
    }
}

 

 

'til' 카테고리의 다른 글

day 9  (0) 2021.12.27
DAY 6  (0) 2021.12.24
DAY 5  (0) 2021.12.23
day2  (0) 2021.12.20
day1  (0) 2021.12.20