行为模式-运算符重载和迭代器
方案1:实现Iterator接口
data class Book(val name: String)
class Bookcase(val books: List<Book>) : Iterator<Book> {
private val iterator: Iterator<Book>
init {
this.iterator = books.iterator()
}
override fun hasNext(): Boolean = this.iterator.hasNext()
override fun next(): Book = this.iterator.next()
}
fun main() {
val bookcase = Bookcase(
listOf(
Book("Kotlin Divide into"),
Book("Thinking in Java")
)
)
while (bookcase.hasNext()){
println("This book name is ${bookcase.next().name}")
}
for(book in bookcase){
println("This book name is ${book.name}")
}
}
Bookcase 对象拥有和List<Book>实例相同的迭代器,我们可以直接调用后者迭代器的所有方法,所以用for 更加简洁的方式也可以
方案2:重载Iterator方法
Kotlin 有更好的方案,用operator重载,内置了很多重载运算符。重载iterator
data class Book(val name: String)
class BookCase2(val books: List<Book>) {
operator fun iterator(): Iterator<Book> = this.books.iterator()
}
瞬间感觉真美好
方案3:通过扩展函数
假设现在Book是引入的一个类,你不能修改它,那么如何用扩展支持迭代
data class Book(val name: String)
class BookCase3(val books: List<Book>){}
operator fun BookCase3.iterator():Iterator<Book> = books.iterator()
如果想要更多的迭代器逻辑控制权,那么可以通过object表达
operator fun BookCase3.iterator():Iterator<Book> = object :Iterator<Book>{
val iterator = books.iterator()
override fun hasNext()=iterator.hasNext()
override fun next()= iterator.next()
}
网友评论