Kotlin 裝飾器模式是一種結構型設計模式,它允許你在不修改原始類的情況下,動態地為對象添加新的功能。在 Kotlin 中,裝飾器模式可以通過擴展函數和委托來實現。以下是如何使用裝飾器模式優化代碼的一些建議:
fun <T> T.printHello(): T {
println("Hello from $this")
return this
}
fun main() {
val myList = listOf(1, 2, 3)
myList.printHello()
}
class Printer(private val message: String) {
fun print() {
println(message)
}
}
class Logger(private val printer: Printer) {
fun log() {
println("Logging: ${printer.message}")
printer.print()
}
}
fun main() {
val printer = Printer("Hello, world!")
val logger = Logger(printer)
logger.log()
}
fun <T> withLogging(message: String, block: T.() -> Unit): T {
println("Logging: $message")
return block()
}
class MyClass {
fun doSomething() {
println("Doing something")
}
}
fun main() {
val myClass = MyClass()
myClass.withLogging("Doing something") {
doSomething()
}
}
interface Component {
fun operation(): String
}
class ConcreteComponent : Component {
override fun operation(): String {
return "ConcreteComponent operation"
}
}
abstract class Decorator(private val component: Component) : Component {
abstract override fun operation(): String
}
class ConcreteDecoratorA(component: Component) : Decorator(component) {
override fun operation(): String {
return "ConcreteDecoratorA($component.operation())"
}
}
class ConcreteDecoratorB(component: Component) : Decorator(component) {
override fun operation(): String {
return "ConcreteDecoratorB($component.operation())"
}
}
fun main() {
val component = ConcreteComponent()
val decoratorA = ConcreteDecoratorA(component)
val decoratorB = ConcreteDecoratorB(decoratorA)
println(decoratorB.operation())
}
通過使用這些方法,你可以使用 Kotlin 裝飾器模式優化代碼,使其更加模塊化和可擴展。