什么是Factory
和Factory2
之间有什么不同?他们似乎都做同样的事情。
data class Car(val horsepowers: Int) {
companion object Factory {
val cars = mutableListOf<Car>()
fun makeCar(horsepowers: Int): Car {
val car = Car(horsepowers)
cars.add(car)
return car
}
}
object Factory2 {
val cars = mutableListOf<Car>()
fun makeCar(horsepowers: Int): Car {
val car = Car(horsepowers)
cars.add(car)
return car
}
}
}
一个同伴对象是一个特定类型的对象声明,允许一个目的是充当类似于在其他语言中静态对象(例如Java)的。添加伴侣的对象声明允许添加的“静态”功能,即使实际静态的概念不存在科特林的对象。