设计模式

迭代器模式(Iterator)

2020-07-18  本文已影响0人  秀儿2020

迭代器模式(Iterator)

定义

提供一种方法顺序访问内部实现不同的聚合对象中的元素,而不需要暴露该对象中的内部表示。所谓聚合是指一组对象的组合结构,比如Java中的集合、数组等。

本质

控制访问聚合对象中的元素。

登场角色

示例代码

/**
 * 定义实现迭代器的接口
 */
public interface Aggregate {
    Iterator iterator();
}


/**
 * 定义迭代器需要实现的方法
 *
 */
public interface Iterator<T> {
    boolean hasNext(); //是否存在下一个元素
    T next(); //返回下一个元素
}


/**
 * 具体的集合
 */
public class BookShelf implements Aggregate{
    private Book[] books;
    private int last;

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

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

    public int getLenth(){
        return last;
    }

    public Book getBook(int index){
        return books[index];
    }
    @Override
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}


/**
 * 具体的迭代器,实现顺序访问集合中元素的方法
 */
public class BookShelfIterator implements Iterator<Book>{
    private BookShelf bookShelf;
    private int index;

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

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

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


/**
 * 集合中的元素
 */
public class Book {
    private String name;
    private String author;

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}


/**
 * 测试
 */
public class RunIterator {
    public static void main(String[] args){
        //初始化集合并添加元素
        BookShelf bookShelf = new BookShelf(10);
        for(int i=0;i<10;i++){
            bookShelf.addBook(new Book("张三"+i,"张三"+i+"的周末"));
        }
        //使用迭代器访问集合中的元素
        Iterator<Book> iterator = bookShelf.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}



运行结果

Book{name='张三0', author='张三0的周末'}
Book{name='张三1', author='张三1的周末'}
Book{name='张三2', author='张三2的周末'}
Book{name='张三3', author='张三3的周末'}
Book{name='张三4', author='张三4的周末'}
Book{name='张三5', author='张三5的周末'}
Book{name='张三6', author='张三6的周末'}
Book{name='张三7', author='张三7的周末'}
Book{name='张三8', author='张三8的周末'}
Book{name='张三9', author='张三9的周末'}

迭代器模式的功能

在于提供对聚合对象的迭代访问。要用统一的方式顺序访问内部实现不同的聚合对象内的元素,按照该思路定义出来的统一的访问方式就是迭代器接口。

迭代器模式的关键思想

把对聚合对象的遍历和访问从聚合对象中分离出来,放入单独的迭代器中。

迭代器模式的优点

上一篇 下一篇

猜你喜欢

热点阅读