3.AbstactFactory - QDDCoder/LZLearniOS GitHub Wiki

抽象工厂模式

 抽象工厂模式Abstract Factory Pattern是围绕一个超级工厂创建其他工厂该超级工厂又称为其他工厂的工厂这种类型的设计模式属于创建型模式它提供了一种创建对象的最佳方式在抽象工厂模式中接口是负责创建一个相关对象的工厂不需要显式指定它们的类每个生成的工厂都能按照工厂模式提供对象

代生产的对象抽象接口/对象

/// 抽象工厂待生产的shape接口
protocol Shape {
    func draw()
}
/// 抽象工厂待生产的Color接口
protocol Color {
    func fill()
}

//抽象工厂待生产的对象
class Rectangle: Shape {
    func draw() {
        print("开始Rectangle的绘画")
    }
}

class Square: NSObject, Shape {
    func draw() {
        print("开始Square的绘画")
    }
}

class Red: Color {
    func fill() {
        print("开始Red的fill")
    }
}

class Yellow: Color {
    func fill() {
        print("开始Yellow的fill")
    }
}

抽象工厂类

/// 抽象工厂类
protocol AbstractFactoryModel {
    func getColor(withColor color:String) -> Color?
    func getShape(withShape shape:String) -> Shape?
}

抽象工厂生产的工厂

/// Shape的工厂
class ShapeFactory: AbstractFactoryModel {
    func getColor(withColor color: String) -> Color? {
        return nil
    }
    
    func getShape(withShape shape: String) -> Shape? {
        if shape == "Rectangle"{
            return Rectangle()
        }else if shape == "Square"{
            return Square()
        }
        return nil
    }
}

/// Color的工厂
class ColorFactory: AbstractFactoryModel {
    func getColor(withColor color: String) -> Color? {
        if color == "Red"{
            return Red()
        }else if color == "Yellow"{
            return Yellow()
        }
        return nil
    }
    
    func getShape(withShape shape: String) -> Shape? {
        return nil
    }
}

工厂的生产

/// 工厂生产类 通过颜色或者形状获取工厂
class FactoryProducer: NSObject {
    /// 单例
    static func getFactory(withChoice choice:String) -> AbstractFactoryModel? {
        if choice == "Shape" {
            return ShapeFactory()
        }else if choice == "Color"{
            return ColorFactory()
        }
        return nil
    }
}
  • 抽象工厂测试类

/// 获取形状工厂
let shapeFactory = FactoryProducer.getFactory(withChoice: "Shape")
//获取形状为Square的对象
if let shape1 = shapeFactory?.getShape(withShape: "Square") {
    shape1.draw()
}

//获取形状为Rectangle
if let shape2 = shapeFactory?.getShape(withShape: "Rectangle") {
    shape2.draw()
}

//获取颜色工厂
let colorFactory = FactoryProducer.getFactory(withChoice: "Color")
//获取red对象
if let color1 = colorFactory?.getColor(withColor: "Red") {
    color1.fill()
}
//获取yellow对象
if let color2 = colorFactory?.getColor(withColor: "Yellow") {
    color2.fill()
}
  • 测试结果

开始Square的绘画
开始Rectangle的绘画
开始Red的fill
开始Yellow的fill
⚠️ **GitHub.com Fallback** ⚠️