kotlin

01设计模式-kotlin-迭代器Iterator

2018-07-06  本文已影响0人  xieyangxuejun

什么是迭代器模式

一句话总结 : 数据集合按照顺序遍历.....

类图显示

现成的书图


直接上代码

public interface Iterator<out T> {
    public operator fun hasNext(): Boolean
    public fun next(): T
}

public interface Aggregate<out T> {
    fun iterator(): Iterator<T>
}

class BookshelfIterator(val shelf: Bookshelf) : Iterator<Book> {
    private var index: Int = 0

    override fun hasNext(): Boolean {
        return if (index < shelf.length() - 1) {
            index++
            true
        } else {
            false
        }
    }

    override fun next(): Book {
        return shelf.get(index)
    }


}

public class Bookshelf : Aggregate<Book> {
    private val books = mutableListOf<Book>()

    fun append(book: Book) {
        books.add(book)
    }

    fun remove(index: Int) {
        books.removeAt(index)
    }

    fun get(index: Int): Book = books[index]

    fun length(): Int = books.size

    override fun iterator(): Iterator<Book> {
        return BookshelfIterator(this)
    }

}

data class Book(var title: String = "标题", val price: Int = 10)

测试运行

fun main(args: Array<String>) {
    Bookshelf().run {
        for (i in 0..10) {
            this.append(Book("title$i", i))
        }
        println(this)
        this.iterator().run {
            while (this.hasNext()) {
                this.next().run {
                    println("${this.title}======${this.price}")
                }
            }
        }
    }
}

运行结果

iterator.Bookshelf@266474c2
title1======1
title2======2
title3======3
title4======4
title5======5
title6======6
title7======7
title8======8
title9======9
title10======10
QQ群:462546711
上一篇 下一篇

猜你喜欢

热点阅读