裝飾器模式(Decorator)
阿新 • • 發佈:2019-01-27
裝飾器模式
動態地給物件新增行為(職責)
假設我們要裝飾 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")
}