在Kotlin中,工廠模式是一種創(chuàng)建型設(shè)計(jì)模式,它提供了一種在不指定具體類的情況下創(chuàng)建對(duì)象的方法。工廠模式通常包括一個(gè)抽象產(chǎn)品(Abstract Product)和一個(gè)或多個(gè)具體產(chǎn)品(Concrete Product)以及一個(gè)工廠接口(Factory Interface)。
以下是在Kotlin中使用工廠模式的示例:
abstract class Shape {
abstract fun area(): Double
}
class Circle(val radius: Double) : Shape() {
override fun area(): Double {
return Math.PI * radius * radius
}
}
class Rectangle(val width: Double, val height: Double) : Shape() {
override fun area(): Double {
return width * height
}
}
interface ShapeFactory {
fun createShape(type: String): Shape
}
class CircleFactory : ShapeFactory {
override fun createShape(type: String): Shape {
return if (type == "circle") Circle(1.0) else throw IllegalArgumentException("Invalid shape type")
}
}
class RectangleFactory : ShapeFactory {
override fun createShape(type: String): Shape {
return if (type == "rectangle") Rectangle(1.0, 1.0) else throw IllegalArgumentException("Invalid shape type")
}
}
fun main() {
val circleFactory = CircleFactory()
val rectangleFactory = RectangleFactory()
val circle = circleFactory.createShape("circle")
val rectangle = rectangleFactory.createShape("rectangle")
println("Circle area: ${circle.area()}")
println("Rectangle area: ${rectangle.area()}")
}
在這個(gè)示例中,我們定義了一個(gè)抽象產(chǎn)品Shape
,兩個(gè)具體產(chǎn)品Circle
和Rectangle
,以及一個(gè)工廠接口ShapeFactory
。我們還創(chuàng)建了兩個(gè)具體工廠CircleFactory
和RectangleFactory
,它們分別負(fù)責(zé)創(chuàng)建Circle
和Rectangle
對(duì)象。最后,我們?cè)?code>main函數(shù)中使用這些工廠來(lái)創(chuàng)建對(duì)象并計(jì)算它們的面積。