12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-06 15:36:36
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在Kotlin中,工厂模式是一种创建型设计模式,它提供了一种在不指定具体类的情况下创建对象的方法。工厂模式通常包括一个抽象产品(Abstract Product)和一个或多个具体产品(Concrete
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在Kotlin中,工厂模式是一种创建型设计模式,它提供了一种在不指定具体类的情况下创建对象的方法。工厂模式通常包括一个抽象产品(Abstract Product)和一个或多个具体产品(Concrete Product)以及一个工厂接口(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()}")}
在这个示例中,我们定义了一个抽象产品Shape
,两个具体产品Circle
和Rectangle
,以及一个工厂接口ShapeFactory
。我们还创建了两个具体工厂CircleFactory
和RectangleFactory
,它们分别负责创建Circle
和Rectangle
对象。最后,我们在main
函数中使用这些工厂来创建对象并计算它们的面积。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19