工厂模式就相当于日常生活中的去买东西,如我们需要去买一辆车,我们不需要去知道车是怎么生产的,我们只需要告诉卖车的我们需什么车,我们就能买这车辆车,工厂模式就是这样,工厂模式的优点是1:当我们想创建一个对象时,只需要知道名称就好了2:拓展性高,如果想增加一个产品,只要扩展一个工厂类就可以了3:屏蔽产品的具体实现,调用者只关心产品的接口。当然工厂模式也有其缺陷1:每一次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,同时也增加了系统类的依赖。
例:1.创建一个接口
interface Shape{
fun draw()
}
2.创建接口的实体类
class Circle: Shape {
override fun draw() {
println("Circle")
}
}
class Rectangle: Shape{
override fun draw() {
println("Rectangle")
}
}
3.创建一个工厂,生成基于给定信息的实体类的对象
class ShapeFactory(){
fun getShape(s: String): Shape{
if (s == "Circle") return Circle()
else if (s == "Rectangle") return Rectangle()
else return object : Shape{
override fun draw() {
println("null")
}
}
}
}
4.使用该工厂,通过传递类型信息来获取实体类的对象
fun main(){
val circle = ShapeFactory().getShape("Circle")
circle.draw()
val rectangle = ShapeFactory().getShape("Rectangle")
rectangle.draw()
}
5.执行程序,输出结果
例2
interface Shape{
fun draw()
companion object Factory{
operator fun invoke(S:ShapeType):Shape{
return when(S){
ShapeType.Rectangle -> return Rectangle()
ShapeType.Circle -> return Circle()
}
}
}
}
enum class ShapeType{
Circle,Rectangle
}
class Rectangle: Shape{
override fun draw() {
println("Rectangle")
}
}
class Circle: Shape{
override fun draw() {
println("Circle")
}
}
fun main(){
val a = Shape.Factory(ShapeType.Rectangle)
a.draw()
}