欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

玩转Kotlin设计模式:第4种——装饰模式解析

最编程 2024-08-06 12:51:00
...

kotli中独有的扩展函数可以很简便的做到装饰模式

class Text(val text: String) {
    fun draw() = print(text)
}

fun Text.underline(decorated: Text.() -> Unit) {
    print("_")
    this.decorated()
    print("_")
}

// usage
Text("Hello").run {
    underline {
        draw()
    }
}

推荐阅读