Kotlin设计模式

来源:互联网 发布:skype聊天软件下载 编辑:程序博客网 时间:2024/06/10 10:21

装饰器模式

动态地给对象添加行为(职责)

假设我们要装饰 Text这个类:

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

为这个Text “装饰” 即 拓展行为

fun main(args: Array<String>) {    Text("Hello").apply {        background {            underline {                draw()            }        }    }}class Text(val text: String) {    fun draw(){        print(text)    }}//用扩展函数 拓展行为fun Text.underline(decorated: Text.() -> Unit) {    print("_")    this.decorated()    print("_")}fun Text.background(decorated: Text.() -> Unit) {    print("\u001B[43m")    this.decorated()    print("\u001B[0m")}
原创粉丝点击