MST

星途 面试题库

面试题:Kotlin DSL 中如何定义可复用的构建器

在 Kotlin DSL 构建领域特定语言的实践中,假设要构建一个简单的图形绘制 DSL。请描述如何定义一个可复用的构建器,用于创建不同类型的图形(如圆形、矩形),并给出相关的 Kotlin 代码示例。
48.4万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

1. 定义图形接口

首先定义一个接口来表示所有图形,这样不同类型的图形都可以实现这个接口。

interface Shape {
    fun draw()
}

2. 定义圆形和矩形类

分别定义圆形和矩形类实现 Shape 接口。

class Circle(private val radius: Double) : Shape {
    override fun draw() {
        println("Drawing a circle with radius $radius")
    }
}

class Rectangle(private val width: Double, private val height: Double) : Shape {
    override fun draw() {
        println("Drawing a rectangle with width $width and height $height")
    }
}

3. 定义图形构建器接口

定义一个构建器接口,用于构建不同类型的图形。

interface ShapeBuilder {
    fun buildCircle(radius: Double): Shape
    fun buildRectangle(width: Double, height: Double): Shape
}

4. 实现图形构建器

实现 ShapeBuilder 接口来创建具体的图形。

class DefaultShapeBuilder : ShapeBuilder {
    override fun buildCircle(radius: Double): Shape {
        return Circle(radius)
    }

    override fun buildRectangle(width: Double, height: Double): Shape {
        return Rectangle(width, height)
    }
}

5. 使用图形构建器

通过构建器来创建图形并绘制。

fun main() {
    val builder = DefaultShapeBuilder()
    val circle = builder.buildCircle(5.0)
    val rectangle = builder.buildRectangle(10.0, 5.0)

    circle.draw()
    rectangle.draw()
}

6. 进一步优化为 Kotlin DSL 风格(使用扩展函数和 lambda)

class ShapeDSL {
    private val shapes = mutableListOf<Shape>()

    fun circle(radius: Double) {
        shapes.add(Circle(radius))
    }

    fun rectangle(width: Double, height: Double) {
        shapes.add(Rectangle(width, height))
    }

    fun drawAll() {
        shapes.forEach { it.draw() }
    }
}

fun shapeBuild(block: ShapeDSL.() -> Unit) {
    val shapeDSL = ShapeDSL()
    shapeDSL.block()
    shapeDSL.drawAll()
}

可以这样使用:

fun main() {
    shapeBuild {
        circle(3.0)
        rectangle(8.0, 4.0)
    }
}