Kotlin 泛型在设计模式中有广泛的应用,它们可以帮助我们编写更加灵活、可复用和类型安全的代码。以下是一些 Kotlin 泛型可以应用于的设计模式:
abstract class Factory<T> {
abstract fun create(): T
}
class StringFactory : Factory<String>() {
override fun create(): String = "Hello, Kotlin!"
}
class Singleton<T> {
private static var instance: T? = null
companion object {
fun <T> getInstance(cls: KClass<T>): T {
return instance ?: synchronized(this) {
instance ?: cls.java.newInstance().also { instance = it }
}
}
}
}
abstract class Adapter<T, R> {
abstract fun adapt(t: T): R
}
class StringLengthAdapter : Adapter<String, Int>() {
override fun adapt(t: String): Int = t.length
}
abstract class Decorator<T> : T {
abstract fun component(): T
}
class LoggingDecorator<T>(private val component: T) : Decorator<T>() {
override fun component(): T = component
override fun toString(): String {
return "LoggingDecorator($component)"
}
}
interface Strategy {
fun execute(): String
}
class UpperCaseStrategy : Strategy {
override fun execute(): String = "Upper case"
}
class LowerCaseStrategy : Strategy {
override fun execute(): String = "Lower case"
}
class StrategyContext<T>(private val strategy: T) {
fun executeStrategy(): String {
return strategy.execute()
}
}
这些设计模式在 Kotlin 中都可以通过泛型来增强其灵活性和类型安全性。