在Kotlin中,當子類需要應對需求變更時,可以采取以下策略:
interface Drawable {
fun draw()
}
class Circle(val radius: Double) : Drawable {
override fun draw() {
println("Drawing a circle with radius $radius")
}
}
class Square(val side: Double) : Drawable {
override fun draw() {
println("Drawing a square with side $side")
}
}
class Engine {
fun start() {
println("Engine started")
}
}
class Car(engine: Engine) {
private val engine = engine
fun startCar() {
engine.start()
println("Car started")
}
}
fun String.formatDate(): String {
// 添加新的日期格式化邏輯
return this + " formatted as YYYY-MM-DD"
}
fun main() {
val date = "2022-01-01"
println(date.formatDate())
}
interface ShippingStrategy {
fun calculateCost(weight: Double): Double
}
class FreeShipping : ShippingStrategy {
override fun calculateCost(weight: Double): Double {
return 0.0
}
}
class FlatRateShipping(val rate: Double) : ShippingStrategy {
override fun calculateCost(weight: Double): Double {
return rate * weight
}
}
class Order(val shippingStrategy: ShippingStrategy, val weight: Double) {
fun calculateTotalCost(): Double {
return shippingStrategy.calculateCost(weight)
}
}
總之,在Kotlin中,通過使用接口和抽象類、組合、擴展函數(shù)和策略模式等設計模式,可以更好地應對需求變更,提高代碼的可維護性和可擴展性。