在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中,通过使用接口和抽象类、组合、扩展函数和策略模式等设计模式,可以更好地应对需求变更,提高代码的可维护性和可扩展性。