Java Design Patterns--Iterator Pattern

1 Iterator Pattern iterator pattern

Purpose: Provide a way to sequentially access the elements of an aggregate object without exposing the object's internal representation;
Implementation: Transfer the responsibility of walking between elements to iterators, not aggregate objects.

1. The iterator pattern is to separate the traversal behavior of the collection object and abstract an iterator class to be responsible, so as not to expose the internal structure of the collection, but also allow external code to transparently access the data inside the collection;
2. There can be multiple traversals on the same aggregate, forward, backward, or bidirectional;
3. Since the iterator mode separates the responsibilities of storing data and traversing data, adding a new aggregate class requires adding a new iterator class accordingly. The number of classes increases in pairs, which increases the complexity of the system to a certain extent.

2 Implementation

Code scenario: put books on a bookshelf, and then traverse the books;
bookshelves are equivalent to a collection, and each book is an element in the collection.

2.1 Code Implementation

Collection interface

/**
 * 集合接口
 */
public interface Aggregate {
    // 获取迭代器
    public Iterator iterator();
}

Collection implementation class: Bookshelf
provides methods to add, delete, get length and get iterator

/**
 * 具体的集合 书架
 */
public class BookShelf implements Aggregate {
    //集合的真实数据结构为数组 不对外展示
    private Book[] books;
    private int index = 0;

    // 好多集合类 都有默认值 超过默认值会扩容
    public BookShelf(int maxSize) {
        // 给数组指定长度
        books = new Book[maxSize];
    }
    // 添加书
    public void addBook(Book book) {
        books[index] = book;
        index++;
    }
    // 通过索引来获取指定的书
    public Book getBook(int index) {
        return books[index];
    }
    // 获取数组长度
    public int getLength() {
        return books.length;
    }
    // 获取书架迭代器
    @Override
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}

Collection element class: book

/**
 * 书本类
 */
public class Book {
    // 书名
    private String name;

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

Iterator interface
provides hasNext(), next() methods

/**
 * 迭代器接口
 */
public interface Iterator {
    // 是否存在下一个
    public boolean hasNext();

    // 获取下一本书
    public Book next();
}

Iterator implementation class

/**
 * 书架迭代器
 */
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 (this.bookShelf.getLength() > index)
            return true;
        else
            return false;
    }

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

2.2 Involving roles

The iterator pattern structure diagram includes the following roles:

Iterator (abstract iterator): It defines the interface for accessing and traversing elements, and declares methods for traversing data elements, such as: first() method for getting the first element, next for accessing the next element () method, hasNext() method for judging whether there is a next element, currentItem() method for obtaining the current element, etc. These methods will be implemented in the specific iterator.

ConcreteIterator (concrete iterator): It implements the abstract iterator interface, completes the traversal of the aggregate object, and records the current position in the aggregate object through the cursor in the concrete iterator. In the concrete implementation, the cursor is usually A non-negative integer representing the position.

Aggregate (abstract aggregate class): It is used to store and manage element objects, declare a createIterator() method to create an iterator object, and act as an abstract iterator factory role.

ConcreteAggregate (concrete aggregate class): It implements the createIterator() method declared in the abstract aggregate class, which returns a ConcreteIterator instance corresponding to the concrete aggregate class.

2.3 call

caller:

public class Client {
    public static void main(String[] args) {
        // 去市场买了个书架
        BookShelf bs = new BookShelf(5);
        // 往书架上添加书
        bs.addBook(new Book("Java 从入门到放弃"));
        bs.addBook(new Book("MySQL 从删库到跑路"));
        bs.addBook(new Book("函数式编程 从入门到懵逼"));
        bs.addBook(new Book("算法概论 从入门到改行"));
        bs.addBook(new Book("僵尸生存法则"));

        // 获取书架的迭代器
        Iterator iterator = bs.iterator();

        // 通过迭代器来遍历书架
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println(book.getName());
        }
    }
}

result:

Java 从入门到放弃
MySQL 从删库到跑路
函数式编程 从入门到懵逼
算法概论 从入门到改行
僵尸生存法则

Code address: click to jump

References:
[1] Graphical Design Patterns/(Japanese) Hiroshi Yuki; translated by Yang Wenxuan. – Beijing: People’s Posts and Telecommunications Press, 2017.1.
[ 2 ] Wikipedia Design
Patterns [ 3 ] Geek Academy WIKI – Design Patterns .
[ 4 ] Rookie Tutorial – Design Patterns .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325462864&siteId=291194637