Help us understand the problem. What is going on with this article?

Kotlinと図で学んでみるデザインパターン -1章 Iteratorパターン-

Iteratorパターン

集合体の実装と、集合体を数え上げる実装を切り分ける

update iterator.png

interface Aggregate {
    fun iterator(): Iterator
}
interface Iterator {
    fun hasNext(): Boolean
    fun next(): Any
}
data class Book(
        val name: String
)
class BookShelf : Aggregate {

    private val books: MutableList<Book> by lazy {
        mutableListOf<Book>()
    }

    private var last: Int = 0

    fun getBookAt(index: Int): Book {
        return books[index]
    }

    fun appendBook(book: Book) {
        books.add(last, book)
        last++
    }

    fun getLength(): Int {
        return last
    }

    override fun iterator(): Iterator {
        return BookShelfIterator(this)
    }
}
class BookShelfIterator(
        private val bookShelf: BookShelf,
        private var index: Int = 0) : Iterator {

    override fun hasNext(): Boolean {
        return index < bookShelf.getLength()
    }

    override fun next(): Any {
        val book = bookShelf.getBookAt(index)
        index++
        return book
    }
}
fun main() {

    val bookShelf = BookShelf()

    bookShelf.apply {
        appendBook(Book("夜と霧"))
        appendBook(Book("愛と幻想のファシズム"))
        appendBook(Book("対岸の彼女"))
        appendBook(Book("不夜城"))
    }

    val iterator = bookShelf.iterator()

    while (iterator.hasNext()) {
        val book = iterator.next() as? Book
        println(book?.name)
    }

}

※ Java 言語で学ぶデザインパターン入門をKotlinと図で理解しようとしている学習用アウトプットです。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away