一、Iterator 迭代器

设计原理:

代码清单:

接口类

public interface Iterator {
    boolean hasNext();
    Object next();
}
public interface Aggregate {
    Iterator iterator();
}

实现类:

public class BookShelf implements Aggregate {
    private int last;
    private Book[] books;

    BookShelf(int maxSize){
        last = 0;
        books = new Book[maxSize];
    }

    public void addBook(Book book){
        books[last]=book;
        last++;
    }

    public Book getBookBylast(int last){
        return  books[last];
    }

    public int Size(){
        return  last;
    }

    @Override
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}
public class BookShelfIterator implements Iterator{

    private BookShelf bookShelf;
    private int index;

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

    @Override
    public boolean hasNext() {
        if(index<bookShelf.Size())
            return true;
        else
            return  false;
    }

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

实体类:

public class Book {
    private String name;

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

    public String getName() {
        return name;
    }

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

测试类

public class Main {
    public static void main(String[] args){
        BookShelf bookShelf = new BookShelf(20);
        bookShelf.addBook(new Book("水浒传"));
        bookShelf.addBook(new Book("西游记"));
        bookShelf.addBook(new Book("三国志"));

        Iterator iterator = bookShelf.iterator();
        while (iterator.hasNext()){
            Book book = (Book)iterator.next();
            System.out.println(book.getName());
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/baizhuang/p/10400123.html