Kotlin 裝飾器模式(Decorator Pattern)是一種結(jié)構(gòu)型設(shè)計(jì)模式,它允許在不修改原始類代碼的情況下,動(dòng)態(tài)地為對(duì)象添加新的功能或行為。裝飾器模式在 Kotlin 中非常實(shí)用,可以應(yīng)用于以下場(chǎng)景:
fun <T> log(message: String, block: T.() -> Unit): T {
return object : T by block {
override fun toString(): String {
return message + super.toString()
}
}
}
fun main() {
val result = log("Before") {
println("Inside the function")
}
println(result)
}
fun <T> authorize(permissions: Set<String>, block: T.() -> Unit): T {
return object : T by block {
override fun checkPermission(permission: String): Boolean {
return permissions.contains(permission)
}
}
}
fun main() {
val authorizedResult = authorize(setOf("READ")) {
println("Inside the function")
}
authorizedResult.checkPermission("WRITE") // true
}
fun <T> cache(block: T.() -> Unit): T {
val cache = mutableMapOf<String, Any>()
return object : T by block {
override fun execute(): Any? {
val key = this::class.toString()
return cache.getOrPut(key) { super.execute() }
}
}
}
fun main() {
val cachedResult = cache {
println("Inside the function")
}
val result = cachedResult.execute() // Inside the function
}
fun <T> measurePerformance(block: T.() -> Unit): T {
return object : T by block {
override fun execute(): Any? {
val startTime = System.currentTimeMillis()
val result = super.execute()
val endTime = System.currentTimeMillis()
println("Execution time: ${endTime - startTime} ms")
return result
}
}
}
fun main() {
val performanceResult = measurePerformance {
println("Inside the function")
}
performanceResult.execute() // Inside the function
}
這些場(chǎng)景僅僅是裝飾器模式在 Kotlin 中的一些應(yīng)用示例,實(shí)際上,只要需要在運(yùn)行時(shí)為對(duì)象添加新的功能或行為,都可以考慮使用裝飾器模式。