Iterator pattern of Java design pattern

Overview: I believe that every developer will face various complex business logic in development. When solving these problems, junior developers will focus on business logic to gradually realize functions, and believe that the required functions will also be realized, but for later maintenance It will become quite troublesome for an update. When the business logic is changed or adjusted, the developer will even rewrite it to meet the requirements. For experienced developers, they will first consider whether they can use that design pattern to solve the problem. Implement functions and use design patterns to improve the logic and scalability of the code. Several years of personal work experience also proves the importance of learning design patterns. Starting from this article, I will introduce a design and development pattern for each article, which is a combing of my own knowledge. Hope to help those in need.

1. Introduction

In the development process, many people will use the for loop to traverse the data set, and output each element step by step according to the coordinates of i. The function of the variable i is abstracted here, and then the Iterator mode, which is the iterator mode, will be discussed today.

2. Classes and Interfaces

  1. First introduce the role of Iterator

  • Iterator : Iterator, an interface for traversing elements, she defines two methods hasNext() and Next();
  • ConcreteIterator : Concrete iterator, the role implements the interface of the iterator, the role must contain the required information to traverse the collection
  • Aggregate : Collection, this role defines the interface for creating Iterator,
  • ConcreteAggregate : A concrete collection that implements the abstract geometry above, has methods for storing and retrieving elements, and has the ability to create concrete Iterator objects
  • Bean : the stored object

We have taken bookstores and books as examples, bookshelves are collections, and books are commodities, which can be stored and obtained on the bookshelves. Let's take a look at the required interfaces and classes:

    • Iterator :Iterator
    • ConcreteIterator:BookIterator;
    • Aggregate:Aggregate
    • ConcreteAggregate:BookStore
    • Bean:Book

Below we create each class and implement its methods as required above:

  • Iterator class
interface Iterator {
    fun  hasNext():Boolean
    fun next() : Any
}

Contains two methods hasNext() to determine whether there is next data, next() gets the current value and moves down, returning an Any

  • BookIterator class
class BookIterator(val bookStore: BookStore) : Iterator{
    var index = 0
    override fun hasNext(): Boolean {
        return index < bookStore.getLength()
    }
    override fun next(): Any {
       val book = bookStore.getBook(index)
        index ++
        return book
    }
}
Implement its two interface methods. Because the collection needs to be traversed, a bookstore object needs to be passed in here. In hasNext, it is judged whether there is next data according to the table below of the collection, and the data is returned in the next method and the index is moved down. .
  • Aggregate: Collection interface
interface Aggregate {
    fun iterator() : Iterator
}
  • BookStore: A concrete collection class that provides storage methods and creates iterators
class BookStore : Store {
    var list = mutableListOf<Book>()
    override fun iterator(): Iterator {
        return BookIterator(this@BookStore)
    }
    fun addBook(book: Book) {
        list.add(book)
    }
    fun getBook(int: Int) : Book {
       return list[int]
    }
    fun getLength():Int{
       return list.size
    }
}

A list is created here to save data, getBook is used to obtain data, addBook is used to add data, and the iterator method creates an iterator object

  • Book Book entity class
data class Book(val name: String ,val money : Int)

3. Code call

bookStore = BookStore()
        bookStore.run {
            for (i in 1..5){
                bookStore.addBook(Book("Android",i*10))
            }
        }
        val iterator = bookStore.iterator()
        while (iterator.hasNext()){
            val book : Book= iterator.next() as Book
            Log.e("book===",book.name + "=="+book.money)
        }

First add five data to the collection, traverse the data with the iterator just now, and output the result:

03-25 13:39:56.056 2962-2962/com.example.wuliangliang.designmodel E/book===: Android==10
03-25 13:39:56.056 2962-2962/com.example.wuliangliang.designmodel E/book===: Android==20
03-25 13:39:56.056 2962-2962/com.example.wuliangliang.designmodel E/book===: Android==30
03-25 13:39:56.056 2962-2962/com.example.wuliangliang.designmodel E/book===: Android==40
03-25 13:39:56.056 2962-2962/com.example.wuliangliang.designmodel E/book===: Android==50

Fourth, expand thinking

  • Why use iterator?
while (iterator.hasNext()){
            val book : Book= iterator.next() as Book
            Log.e("book===",book.name + "=="+book.money)
        }

Only the method of Iterator is used here, and no method of BookStroe is used, which realizes the decoupling of traversal and collection

  • Why use Aggregate and Iterator interfaces

Some people may think that the specific classes of BookStore and BookIterator here can be more functional, why do you need two collections? For such students, they only want to use specific classes to solve the actual method, but in this case, these classes are coupled and limited together, and the decoupling of operation logic and data is not realized, which makes it easier for classes to be regarded as components use again.

Well, today's design patterns are here. I hope you can use design patterns better in your work in the future. Slowly you will find that design patterns are really powerful, and simple principles can achieve many complex functions.


Guess you like

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