A simple understanding of Java design patterns: iterator pattern (reproduced)

Iterator pattern definition

Iterator mode (Iterator) provides a way to sequentially access various elements in an aggregated object without exposing the internal representation of the object.

Traversal is commonly used during Java development. The following side program:

for(int i =0 ;i<arr.length;i++){
    
    
    System.out.println(arr[i]);
}

In the for statement, i++ increments by 1 each time it loops, and iterates to the next element. The pattern formed after abstracting and generalizing the role of loop variables becomes the Iterator pattern in the design pattern.

Realization scenario

Put the book (Book) in the bookshelf (BookShelf) and display the book titles in order.
Insert picture description here
Insert picture description here

Program example

Aggregate interface:
The interface of the collection to be traversed. A class that implements this interface will become a collection that can store multiple elements, similar to an array.

public interface Aggregate{
    
    
    public abstract Iterator iterator();
}

The method declared in the Aggregate interface is iterator, which is used to generate an iterator for traversal.

Iterator interface: It
is used to traverse the elements in the collection, which is equivalent to the loop variable in the loop statement (for(int i =0; i<arr.lenth; i++), which specifically implements a sequential traversal iterator.

public interface Iterator{
    
    
    public abstract boolean hasNext();
    public abstract Object next();
}

The hasNext() method determines whether there is the next one, and the next() method gets the next element.

Under special instructions, when the next method gets the element, it adds one to the count of the next element. Get the current element and point to the next element.

Book class:
general class, book title field getName () method to get the book title. The constructor initializes the title of the book.

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

BookShelf class: The
bookshelf class, as a collection class for storing books, implements the Aggregate interface. It implements the iterator method of the Aggregate interface.

public class BookShelf implements Aggregate {
    
    

    private List<Book> books;


    public BookShelf() {
    
    
        this.books = new ArrayList<Book>();
    }

    public Book getBookAt(int index) {
    
    
        return books.get(index);
    }

    public void appendBook(Book book) {
    
    
        books.add(book);
    }

    public int getLength() {
    
    
        return books.size();
    }

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

The main point is the iterator method, which returns the BookShelfIterator class to be used when traversing the bookshelf as the iterator of the bookshelf. This method will be called when the outside world wants to traverse the bookshelf.

BookShelfIterator class:

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;
        } else {
    
    
            return false;
        }
    }


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

As an iterator, it needs to implement the Iterator interface. index is the index currently pointed to by the iterator.
hasNext determines whether there is a next book. Judge by comparing the subscript and the total.
Next gets the current book and points to the next one.

Main class:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        BookShelf bookShelf = new BookShelf();
        bookShelf.appendBook(new Book("Around the World in 80 Days"));
        bookShelf.appendBook(new Book("Bible"));
        bookShelf.appendBook(new Book("Cinderella"));
        bookShelf.appendBook(new Book("Daddy-Long-Legs"));
        Iterator it = bookShelf.iterator();
        while (it.hasNext()) {
    
    
            Book book = (Book) it.next();
            System.out.println(book.getName());
        }
    }
}

控制台:
----------------------------------
Around the World in 80 Days
Bible
Cinderella
Daddy-Long-Legs
----------------------------------

The role of each role in the Iterator mode

  • Iterator: This role is responsible for defining the interface of traversing elements one by one in order. In the program, played by the Iterator interface, two methods haveNext and next are defined.
  • Concretelterator (specific iterator): This role is responsible for implementing the interface defined by the Iterator role. This role contains the information necessary to traverse the collection.
  • Aggregate: This role is responsible for defining the interface for creating the Iterator role. This interface is a method that creates one, and accesses the people stored in my internal elements in order.
  • ConcreteAggregate (specific collection): This role is responsible for implementing the interface defined by the Aggregate role. He will create a specific Iterator role, which is ConcreteIterator, which is the BookShelf in the example.

Class diagram of Iterator mode:
Insert picture description here

The focus of learning design patterns.
Iterator can be used no matter how the implementation changes.
Why should we consider introducing the complex design pattern of Iterator?

If it is an array, can't it be traversed directly with the for fantasy statement?

Why introduce the Iterator role outside of the collection?

An important reason: the introduction of Iterator can separate the traversal from the implementation.

while (it.hasNext()) { Book book = (Book) it.next() ; System.out.println(book.getName()); } Iterator’s hasNext method and next method are used here, and BookShelf is not called Methods. In other words, the while loop here does not depend on the implementation of BookShelf.



For example, the developers at BookShelf decided to abandon the use of arrays to manage books, and instead use Java.util.Vector instead, what will happen. No matter how BookShelf changes, as long as BookShelf's iterator method can correctly return the strength of Iterator, the code can work normally even without any modification to the while loop above.

It's really convenient for the caller of BookShelf.

The role of design patterns is to help us write reusable classes.

The so-called reusable refers to the realization of a class as a component. When a component changes, other components do not need to be modified or only a small modification is required to deal with it.

This can also understand why the return value of the iterator method in the sample program is not the bookshelfiter class but the iter type. This shows that the program is to use the iterator method for programming rather than the bookshelfiterator method.

Difficult to
understand abstract classes and interfaces People who are difficult to understand abstract classes and interfaces often consume ConcreteAggregate roles and ConcreteIterator role programming instead of Aggregate interfaces and Iterator interfaces. They always want to use concrete classes to solve all the problems. ?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

However, if only specific classes are used to solve the problem, it is easy to cause strong coupling between classes, and these classes are also difficult to be reused as components. In order to weaken the coupling between classes and make it easier for classes to be reused as components, We need to introduce abstract classes and interfaces.
This kind of thinking should run through the entire design pattern.

Correspondence between Aggregate and Iterator It is a feature of Iterator mode that
multiple Iterators
will traverse functions outside of the role of Aggregate. This feature can write multiple ConcreteIterator roles for a ConcreteAggregate role.

Introduce several design patterns in advance:

Vistor mode
iterator mode is to take out the elements one by one from the collection for traversal, but it does not do any processing on the taken out elements in the Iterator interface.

The Vistor mode performs the same processing on the elements in the process of traversing the collection of elements.

In the process of traversing the collection, it is a common requirement to perform fixed processing on the elements. The visitor model appeared in response to this demand. The same process is performed on the elements in the process of the collection of the square elements. This mode is the Vistor mode.

Composite mode
Composite mode is a mode with a recursive structure, in which iterator mode is more difficult to use.

Factory Method Mode The Factory Method mode
may be used when generating the power of Iterator in the iterator method.

Author: toot bumper rattled
link: https: //www.jianshu.com/p/3dd7b4e73561
Source: Jane books
are copyrighted by the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_34365173/article/details/108560624
Recommended