Static Factory Methods in Kotlin

Posted on By ᵇᵒ

优雅高效的Kotlin静态工厂方法:

interface Car {
    val price: Int

    companion object {
        operator fun invoke(brand: Brand): Car {
            return when (brand) {
                Brand.Audi -> Audi()
                Brand.Bmw -> Bmw()
                Brand.Benz -> Benz()
            }
        }
    }
}

sealed class Brand {
    object Audi : Brand()
    object Bmw : Brand()
    object Benz : Brand()
}

class Audi : Car {
    override val price = 300000
}

class Bmw : Car {
    override val price = 400000
}

class Benz : Car {
    override val price = 500000
}

fun main() {
    val car = Car(Brand.Audi)
    println(car.price)
}