使用Build模式构建一个data类
data class Car private constructor(
val make: String,
val model: String,
val year: Int,
val color: String,
val engine: Engine,
val options: List<String>,
val price: Double
) {
class Builder {
private var make: String = ""
private var model: String = ""
private var year: Int = 0
private var color: String = ""
private var engine: Engine = Engine()
private val options = mutableListOf<String>()
private var price: Double = 0.0
fun setMake(make: String) = apply { this.make = make }
fun setModel(model: String) = apply { this.model = model }
fun setYear(year: Int) = apply { this.year = year }
fun setColor(color: String) = apply { this.color = color }
fun setEngine(engine: Engine) = apply { this.engine = engine }
fun addOption(option: String) = apply { options.add(option) }
fun setPrice(price: Double) = apply { this.price = price }
fun build(): Car {
require(price > 0) { "Price must be greater than zero." }
return Car(make, model, year, color, engine, options.toList(), price)
}
}
}
data class Engine(val horsepower: Int, val displacement: Double)
fun main() {
val car = Car.Builder()
.setMake("Toyota")
.setModel("Camry")
.setYear(2023)
.setColor("Blue")
.setEngine(Engine(200, 2.5))
.addOption("Leather Seats")
.addOption("Sunroof")
.setPrice(30_000.0)
.build()
println(car)
}