interface Iterator{
public boolean hasNext();
public Object next();
}
class Book
{
private String name;
public Book(String n){
name = n;
}
public String getName(){
return name;
}
};
interface Aggregate{
public Iterator iterator();
}
class BookShelf implements Aggregate
{
private Book[] books = null;
private int last = 0;
public BookShelf(int maxsize){
books = new Book[maxsize];
}
public int getLength(){
return last;
}
public void append(Book book){
books[last++] = book;
}
public Iterator iterator(){
return new BookShelfIterator(this);
}
public Book getBookAt(int index){
return books[index];
}
};
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;
}
};
public class IteratorPattern
{
public static void main(String[] args){
BookShelf bookShelf = new BookShelf(4);
bookShelf.append(new Book("Around the world in 80 days"));
bookShelf.append(new Book("Bible"));
bookShelf.append(new Book("Cinderella"));
bookShelf.append(new Book("Daddy-Long-Legs"));
System.out.println("HelloWorld");
Iterator it = bookShelf.iterator();
while (it.hasNext())
{
Book book = (Book)it.next();
System.out.println(" "+book.getName());
}
}
};
Iterator Pattern
最新推荐文章于 2023-05-27 14:33:49 发布