栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式 学习笔记:抽象工厂模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式 学习笔记:抽象工厂模式

抽象工厂模式就相当于是工厂的工厂模式,是围绕一个超级工厂去创建其他工厂。这种类型的设计模式属于创建型模式。它的优点是1:当一个产品族中的多个对象被设计成一起工作时,他能保证客户端始终只使用一个产品族中的对象缺点是1:产品族扩展非常困难,要增加一个系列的某一产品,既要在抽象的Creator中增加代码,又要在具体里增加代码。

例:1.为形状创建一个接口

interface Shape{
    fun draw()
}

2.创建实现接口的实体类

class Rectangle: Shape{
    override fun draw() {
        println("Rectangle")
    }
}
class Circle: Shape{
    override fun draw() {
        println("Circle")
    }
}

3.为颜色创建一个接口

interface Color{
    fun fill()
}

4.创建实现接口的实体类

class Red: Color{
    override fun fill() {
        println("Red")
    }
}
class Green: Color{
    override fun fill() {
        println("Green")
    }
}

5.为Color和Shape对象创建抽象类来获取工厂

abstract class AbstractFactory{
    abstract fun getShape(s: String): Shape
    abstract fun getColor(s: String): Color
}

6.创建扩展了AbstractFactory的工厂类,基于给定的信息生成实体类的对象

class ShapeFactory: AbstractFactory() {
    override 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")
            }
        }
    }
    override fun getColor(s: String): Color {
        TODO("Not yet implemented")
    }
}
class ColorFactory: AbstractFactory(){
    override fun getColor(s: String): Color {
        if (s == "Red") return Red()
        else if (s == "Green") return Green()
        else return object : Color{
            override fun fill() {
                println("null")
            }
        }
    }

    override fun getShape(s: String): Shape {
        TODO("Not yet implemented")
    }
}

7.创建一个工厂创造器/生成器类,通过传递形状或颜色信息来获取工厂

class FactoryProducer{
    fun getFactory(s: String): AbstractFactory{
        if (s == "Shape") return ShapeFactory()
        else if (s == "Color") return ColorFactory()
        else return object : AbstractFactory(){
            override fun getShape(s: String): Shape {
                TODO("Not yet implemented")
            }

            override fun getColor(s: String): Color {
                TODO("Not yet implemented")
            }

        }
    }
}

8.使用FactoryProducer来获取AbstractFactory,通过传递类型信息来获取实体类的对象

fun main(){
    val colorfactory = FactoryProducer().getFactory("Color")
    colorfactory.getColor("Red").fill()
    val shapefactory = FactoryProducer().getFactory("Shape")
    shapefactory.getShape("Circle").draw()
}

9.执行程序,输出结果

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/293251.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号