Author:Gorit
Date:2020/12/1
Refer:《图解设计模式》

一、Iterator 模式

1.1 Iterator 由来

我们常见的循环遍历的方式

  1. int[] arr = new int[199];
  2. for (int i=0;i<arr.length;i++) {
  3. ...
  4. }

这里的循环变量 i 的作用抽象化,通用化后形成的模式,在设计模式中称为 Iterator 模式

用于在数据集合中按照顺序遍历集合,iterator 有反复做某件事的意思,因此称为“迭代器”

1.2 实现 Iterator

我们将编写一个将书 (Book) 放入书架(BookShelf),并将书的名字按顺序显示出来,需要用到如下模块

类(接口) 功能
Aggregate 接口 所要遍历的集合的接口,实现该接口的类将成为一个可以多个元素的集合,就像数组一样
Iterator 接口 遍历集合的接口
Book 类 表示书的类
BookShelf 类 表示书架的类
BookShelfIterator 遍历书架的类
Main 测试

Aggregate 接口

  1. package Iterator;
  2. public interface Aggregate {
  3. // 该方法会生成一个用于遍历集合的迭代器,当需要遍历集合的元素时,可以调用该方法
  4. public abstract Iterator iterator();
  5. }

Iterator 接口

  1. package Iterator;
  2. /**
  3. * 用于遍历集合中的元素,相当于循环中的循环变量
  4. * 以下实现了一个最简单的 Iterator 接口
  5. */
  6. public interface Iterator {
  7. public abstract boolean hasNext(); // 是否有下一个元素
  8. public abstract Object next(); // 下一个元素的值
  9. }

Book 类

  1. package Iterator;
  2. /**
  3. * 书籍的最小实体
  4. */
  5. public class Book {
  6. private String name;
  7. public Book(String name) {
  8. this.name = name;
  9. }
  10. public String getName() {
  11. return name;
  12. }
  13. }

BookShelf 类

  1. package Iterator;
  2. /**
  3. * 表示书架的类,改类需要作为集合保存 所有的书籍,因此需要实现 Aggregate 接口
  4. */
  5. public class BookShelf implements Aggregate {
  6. private Book[] books;
  7. private int last = 0;
  8. public BookShelf(int maxsize) {
  9. this.books = new Book[maxsize];
  10. }
  11. public Book getBookAt(int index) {
  12. return books[index];
  13. }
  14. public void appendBook(Book book) {
  15. this.books[last] = book;
  16. last++;
  17. }
  18. public int getLength() {
  19. return last;
  20. }
  21. // ps 当外部想要遍历书架时,就会调用这个方法:
  22. public Iterator iterator() {
  23. return new BookShelfIterator(this);
  24. }
  25. }

BookShelfIterator 类

package Iterator;

/**
 * 用于遍历书架的 BookShelfIterator 类
 * 该接口要发挥 Iterator 的作用,因此要实现 Iterator接口
 */
public class BookShelfIterator implements Iterator {
    // 要遍历的书架
    private BookShelf bookShelf;
    private int index;

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

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

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

Main

package Iterator;

public class Main {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("A"));
        bookShelf.appendBook(new Book("B"));
        bookShelf.appendBook(new Book("C"));
        bookShelf.appendBook(new Book("D"));
        Iterator it =  bookShelf.iterator();
        while (it.hasNext()) {
            Book book = (Book) it.next();
            System.out.println(book.getName());
        }
    }
}

image.png