読者です 読者をやめる 読者になる 読者になる

Iteratorパターン

今更ながらデザインパターンを勉強を開始。基礎が大事。
Iteratorパターン。練習問題をジェネリックも意識して解いてみました。
ジェネリックにするとキャスト不要で安全です。

// Aggregate.java
public interface Aggregate<T> {
	public abstract Iterator<T> iterator();
}

// BookShelf.java
import java.util.ArrayList;
import java.util.List;

public class BookShelf implements Aggregate<Book> {
	private List<Book> books;
	private int last;

	public BookShelf() {
		this.books = new ArrayList<Book>();
	}

	public Book getBookAt(int index) {
		return books.get(index);
	}

	public void addBook(Book book) {
		this.books.add(book);
		last++;
	}

	public int getLength() {
		return last;
	}

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

// Book.java
public class Book {
	private String name;

	public Book(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

// Iterator.java
public interface Iterator<T> {
	public abstract boolean hasNext();

	public abstract T next();
}

// BookShelfIterator.java
public class BookShelfIterator implements Iterator<Book> {
	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;
		}
		return false;
	}

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

}

// Main.java
public class Main {

	public static void main(String[] args) {
		BookShelf bookshelf = new BookShelf();
		for (int i = 0; i < 10; i++) {
			bookshelf.addBook(new Book("Book-" + String.valueOf(i)));
		}
		Iterator<Book> it = bookshelf.iterator();
		while (it.hasNext()) {
			System.out.println(it.next().getName());
		}
	}

}

出力は

Book-0
Book-1
Book-2
Book-3
Book-4
Book-5
Book-6
Book-7
Book-8
Book-9