首页 > 代码库 > 迭代器模式

迭代器模式

集合类中包含很多数据结构:数组、散列表、ArrayList等,这些集合类的迭代方法都不一样。为了隐藏迭代的具体实现 ,抽象集合类中引用抽象迭代器,具体的集合类引用具体的迭代类,在具体迭代类实现便利具体集合类的方法

技术分享

 

package iterator;

import java.util.Iterator;

/**
 * 抽象集合类,引用抽象迭代类
 */
public interface Aggregate {
    public abstract Iterator iterator();
}

 

package iterator;

/**
 * Created by marcopan on 17/4/7.
 */
public 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;
    }
}

 

package iterator;

import java.util.Iterator;

/**
 * 具体集合类
 */
public class BookShelf implements Aggregate {
    Book[] books;
    int index = 0;

    public BookShelf(int maxium) {
        books = new Book[maxium];
    }

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

    public void appendBook(Book newBook) {
        books[index++] = newBook;
    }

    public int getLength() {
        return index;
    }

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

 

package iterator;

import java.util.Iterator;

/**
 * 具体迭代类,Iterator是抽象迭代类
 */
public class BookShelfIterator implements Iterator {
    private BookShelf bookShelf;
    private int index = 0;

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

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

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

 

package iterator;

import java.util.Iterator;

/**
 * Created by marcopan on 17/4/7.
 */
public class IteratorTest {
    public static void main(String[] args) {
        BookShelf shelf = new BookShelf(4);
        shelf.appendBook(new Book("a"));
        shelf.appendBook(new Book("b"));
        shelf.appendBook(new Book("c"));
        shelf.appendBook(new Book("d"));
        Iterator it = shelf.iterator();
        while (it.hasNext()) {
            Book book = (Book)it.next();
            System.out.println(book.getName());
        }
    }
}

 

迭代器模式