MST

星途 面试题库

面试题:Kotlin类型安全构建器模式在复杂对象构建中的应用

假设有一个电商订单类Order,它包含订单编号、客户信息(客户类包含姓名、联系方式等)、商品列表(商品类包含商品名、价格等),请使用Kotlin的类型安全构建器模式来构建Order实例,展示如何处理多层嵌套对象以及列表的构建,同时要确保类型安全和代码的简洁性。
39.1万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
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)
}