在Kotlin中,接口實(shí)現(xiàn)確保了代碼的穩(wěn)定性和可維護(hù)性。為了確保接口實(shí)現(xiàn)的穩(wěn)定性,可以遵循以下幾點(diǎn):
sealed class Shape {
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
}
abstract class Shape {
abstract fun area(): Double
}
class Circle(radius: Double) : Shape() {
override fun area(): Double = Math.PI * radius * radius
}
class Rectangle(width: Double, height: Double) : Shape() {
override fun area(): Double = width * height
}
expect
和actual
關(guān)鍵字來(lái)定義一個(gè)期望的接口實(shí)現(xiàn)。這有助于確保在不同平臺(tái)或庫(kù)中實(shí)現(xiàn)相同的接口,從而提高代碼的穩(wěn)定性。expect class Shape {
fun area(): Double
}
actual class Circle(radius: Double) : Shape {
override fun area(): Double = Math.PI * radius * radius
}
actual class Rectangle(width: Double, height: Double) : Shape {
override fun area(): Double = width * height
}
object ShapeRepository {
private var instance: ShapeRepository? = null
fun getInstance(): ShapeRepository {
return instance ?: synchronized(this) {
instance ?: ShapeRepository().also { instance = it }
}
}
fun getShape(type: String): Shape? {
// 根據(jù)類型返回相應(yīng)的Shape實(shí)例
}
}
遵循以上幾點(diǎn),可以幫助你在Kotlin中確保接口實(shí)現(xiàn)的穩(wěn)定性。