java : Iterator Pattern

来源:互联网 发布:newsql数据库有哪些 编辑:程序博客网 时间:2024/06/06 07:43
//----------------Iterator Pattern-----------------//返回Iterator实例的接口interface Aggregate{    public Iterator iterator();}interface Iterator{    public boolean hasNext();    public Object next();}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;    }    @Override    public String toString() {        return name+" ";    }}class BookShelf implements Aggregate{    private Book[] books;    private int size = 0;    public BookShelf(int maxSize){        this.books = new Book[maxSize];    }    public Book getBookAt(int target){        return books[target];    }    public BookShelf appendBook(Book book){        books[size] = book;        size++;        return this;    }    public int getLength(){        return size;    }    @Override    public Iterator iterator() {        return new BookShelfIterator(this);  //对应Iterator实现类中的构造方法    }}class BookShelfIterator implements Iterator{    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;        else{            return false;        }    }    @Override    public Object next() {        Book book = (Book)bookShelf.getBookAt(index);        index++;        return book;    }}public class Test3 {    public static void main(String[] args) throws Exception {        BookShelf bs = new BookShelf(5);        bs.appendBook(new Book("A")).appendBook(new Book("B"))            .appendBook(new Book("C")).appendBook(new Book("D")).appendBook(new Book("E"));        BookShelfIterator bsi = new BookShelfIterator(bs);        while(bsi.hasNext())        {            System.out.println(bsi.next());        }    }}/** * 更进一步的,可以把类所接受的类型改成泛型 */
0 0