行为模式---迭代器模式(游标模式)

迭代器模式也叫游标模式主要用来解决遍历集合问题,也可以使用foreach进行遍历,这里主要举例使用如何使用java的Iterable和Iterator实现迭代器模式
类图
这里写图片描述
此图省略了两个接口类
可迭代类:

import java.util.Iterator;

public class BookShelf implements Iterable<Book> {
    private Book[] books;
    private int lastIndex;

    public int getLength() {
        return books.length;
    }

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

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

    public void add(Book book) {
        books[lastIndex] = book;
        lastIndex++;
    }

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

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

    @Override
    public String toString() {
        return "Book [name=" + name + "]";
    }
}

迭代器类:

import java.util.Iterator;

public class BookShelfIterator implements Iterator<Book> {
    private BookShelf bookShelf;
    private int index;

    public BookShelfIterator(BookShelf bookShelf) {
        this.bookShelf = bookShelf;
    }

    @Override
    public boolean hasNext() {
        if (index >= bookShelf.getLength()) {
            return false;
        }
        return true;
    }

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

客户端:

public class Client {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(3);
        bookShelf.add(new Book("book1"));
        bookShelf.add(new Book("book2"));
        bookShelf.add(new Book("book3"));
        //可以直接使用foreach
        for (Book book : bookShelf) {
            System.out.println(book);
        }
    }
}

输出:

Book [name=book1]
Book [name=book2]
Book [name=book3]

猜你喜欢

转载自blog.csdn.net/weixin_43060721/article/details/82391009