面试题答案
一键面试class Customer(val name: String, val contact: String)
class Product(val name: String, val price: Double)
class Order(val orderId: String, val customer: Customer, val products: List<Product>)
class OrderBuilder {
private var orderId: String = ""
private var customer: Customer? = null
private val products = mutableListOf<Product>()
fun orderId(id: String): OrderBuilder {
orderId = id
return this
}
fun customer(builder: CustomerBuilder.() -> Unit): OrderBuilder {
val customerBuilder = CustomerBuilder()
customerBuilder.builder()
customer = customerBuilder.build()
return this
}
fun product(builder: ProductBuilder.() -> Unit): OrderBuilder {
val productBuilder = ProductBuilder()
productBuilder.builder()
products.add(productBuilder.build())
return this
}
fun build(): Order {
require(orderId.isNotEmpty()) { "Order ID cannot be empty" }
require(customer != null) { "Customer cannot be null" }
require(products.isNotEmpty()) { "Products list cannot be empty" }
return Order(orderId, customer!!, products)
}
}
class CustomerBuilder {
private var name: String = ""
private var contact: String = ""
fun name(name: String): CustomerBuilder {
this.name = name
return this
}
fun contact(contact: String): CustomerBuilder {
this.contact = contact
return this
}
fun build(): Customer {
require(name.isNotEmpty()) { "Customer name cannot be empty" }
require(contact.isNotEmpty()) { "Customer contact cannot be empty" }
return Customer(name, contact)
}
}
class ProductBuilder {
private var name: String = ""
private var price: Double = 0.0
fun name(name: String): ProductBuilder {
this.name = name
return this
}
fun price(price: Double): ProductBuilder {
this.price = price
return this
}
fun build(): Product {
require(name.isNotEmpty()) { "Product name cannot be empty" }
require(price > 0) { "Product price must be greater than zero" }
return Product(name, price)
}
}
fun order(block: OrderBuilder.() -> Unit): Order {
val orderBuilder = OrderBuilder()
orderBuilder.block()
return orderBuilder.build()
}
你可以这样使用:
fun main() {
val myOrder = order {
orderId("12345")
customer {
name("John Doe")
contact("123-456-7890")
}
product {
name("Laptop")
price(1000.0)
}
product {
name("Mouse")
price(50.0)
}
}
println(myOrder)
}