Kotlin 裝飾器模式(Decorator Pattern)是一種結構型設計模式,它允許在不修改原始類代碼的情況下,動態地為對象添加新的功能或行為。裝飾器模式在 Kotlin 中非常實用,可以應用于以下場景:
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
}
這些場景僅僅是裝飾器模式在 Kotlin 中的一些應用示例,實際上,只要需要在運行時為對象添加新的功能或行為,都可以考慮使用裝飾器模式。