在Kotlin中,接口实现确保了代码的稳定性和可维护性。为了确保接口实现的稳定性,可以遵循以下几点:
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
关键字来定义一个期望的接口实现。这有助于确保在不同平台或库中实现相同的接口,从而提高代码的稳定性。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? {
// 根据类型返回相应的Shape实例
}
}
遵循以上几点,可以帮助你在Kotlin中确保接口实现的稳定性。