文章

设计模式之工厂模式

Factory

定义

定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。

实现

定义一个Shape协议,里面包含一个draw方法

1
2
3
protocol Shape {
    func draw()
}

定义类Rectangle,Square和Circle,他们都实现了Shape协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Rectangle: Shape {
    func draw() {
        print("Rectangle draw")
    }
}

class Square: Shape {
    func draw() {
        print("Square draw")
    }
}

class Circle: Shape {
    func draw() {
        print("Circle draw")
    }
}

定义ShapeFactory类,根据不同的shapeType构造不同的Shape

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ShapeFactory {
    func getShape(shapeType: String?) -> Shape? {
        if shapeType == nil {
            return nil
        }
        if shapeType == "RECTANGLE" {
            return Rectangle()
        } else if shapeType == "SQUARE" {
            return Square()
        } else if shapeType == "CIRCLE" {
            return Circle()
        }
        return nil
    }
}

使用:

1
2
3
let factory = ShapeFactory()
let shape = factory.getShape(shapeType: "RECTANGLE")
shape?.draw()

输出:

1
Rectangle draw

源码下载

本文由作者按照 CC BY 4.0 进行授权