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 中都可以通過泛型來增強其靈活性和類型安全性。