图解设计模式 Iterator 模式

Iterator设计模式UML图

《图解设计模式 Iterator 模式》

Paste_Image.png

Iterator(迭代器)

//负责定义按顺序遍历各个元素的接口
package me.maweiyi;


/** * Created by MWY * Date: 1/10/17 * Time: 22:10 */
public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

ConcreteIterator(具体的迭代器)

//负责实现具体的迭代器
package me.maweiyi;

/** * Created by MWY * Date: 1/10/17 * Time: 22:21 */
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() {
        //return false;
        if (index < bookShelf.getLength()) {
            return true;
        } else {
            return false;
        }
    }

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

Aggregate(集合)

//负责定义创建Iterator的接口
package me.maweiyi;

/** * Created by MWY * Date: 1/10/17 * Time: 22:09 */
public interface Aggregate {
    public abstract Iterator iterator(); }

ConcreteAggregate(具体的集合)

//实现Aggregate创建的接口,创建出具体的Iterator
package me.maweiyi;

/** * Created by MWY * Date: 1/10/17 * Time: 22:15 */
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;
    }

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

Iterator设计模式的优点

  • 将遍历和实现分开
    原文作者:算法小白
    原文地址: https://juejin.im/entry/587596a3a22b9d0058a743f5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞