侧边栏壁纸
博主头像
千异博主等级

学无止境,学以致用,志存高远!

  • 累计撰写 29 篇文章
  • 累计创建 24 个标签
  • 累计收到 0 条评论

Gof——Iterator模式(迭代器模式)

千异
2022-04-24 / 0 评论 / 0 点赞 / 128 阅读 / 1,680 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-24,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
package xin.jiangqiang.iterator;

public interface Aggregate<Book> {
    Iterator<Book> iterator();
}
package xin.jiangqiang.iterator;

/**
 * 书的类
 */
public class Book {
    private String name;

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

    public String getName() {
        return name;
    }
}
package xin.jiangqiang.iterator;

/**
 * 书架类
 */
public class BookShelf implements Aggregate<Book> {
    private Book[] books;//使用数组存储书架中的书
    private int last = 0;//实际存储的书本数

    /**
     * @param maxSize 书架容量
     */
    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;
    }

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

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;
        } else {
            return false;
        }
    }

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

}
package xin.jiangqiang.iterator;

public interface Iterator<Book> {
    boolean hasNext();

    Book next();
}
package xin.jiangqiang.iterator;

public class Main {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("Around the World in 80 Days"));
        bookShelf.appendBook(new Book("Bible"));
        bookShelf.appendBook(new Book("Cinderella"));
        bookShelf.appendBook(new Book("Daddy-Long-Legs"));
        Iterator<Book> iterator = bookShelf.iterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println(book.getName());
        }
    }
}
0
博主关闭了所有页面的评论