设计模式之Iterator模式

74 阅读1分钟

通常,我们使用java遍历数组时会使用这样的for循环进行遍历数组。

for(int i = 0; i < arr.length; i++){
    System.out.println(arr[i]);
}

将上述程序中的i带作用抽象化、通用化后形成的模式就是Iterator模式。先看一段程序,这段程序通过描述了书本和书架的关系来解释了Iterator模式。

Aggregate接口,定义了创建Iterator接口的(抽象)方法。

public interface Aggregate {
    public abstract Iterator iterator();
}

Iterator接口,负责定义按顺序遍历元素的接口。

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

Book类

public class Book {
    private String name;
    public Book(String name){this.name = name;}
    public String getName(){return name;}
}

BookShelf类(书架类),定义了书架放书、遍历书的方法。

public class BookShelf implements Aggregate{
    private Book[] books;
    private int last = 0;
    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;
    }
    public Iterator iterator(){
        return new BookShelfIterator(this);
    }
}

BookShelfIterator类,具体的迭代器

public 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  = bookShelf.getBookAt(index);
        index++;
        return book;
    }
}

主函数main

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 it = bookShelf.iterator();
        while (it.hasNext()){
            Book book = (Book) it.next();
            System.out.println(book.getName());
        }
    }
}

程序中定义了迭代器的创建接口,书架类通过实现Aggregate接口实现抽象方法来创建迭代器对象,通过迭代器对象来对元素进行遍历。
使用Iterator的好处就是,如果我们现在不想用数组来存储了,可能要换成ArrayList,很方便就换了,Iterator模式弱化了类之间的耦合性。Iterator中的hasNext与next方法与BookShelf无关,我们不用管BookShelf如何变化,只要BookShelf的iterator方法能够正确的返回Iterator的实例就行。