Nov 11

Factory Method in Swift

protocol AbstractObject {
    static func create() -> AbstractObject
    func doStuff()
}

extension AbstractObject {
    func doStuff() {
        let className = String(describing: self)
        print("\(className).doStuff()")
    }
}

class ConcreteObject: AbstractObject {

    private init() {}

    static func create() -> AbstractObject {
        return ConcreteObject()
    }
}

class SteelObject: AbstractObject {

    private init() {}

    static func create() -> AbstractObject {
        return SteelObject()
    }
}

let concrete = ConcreteObject.create()
let steel = SteelObject.create()
concrete.doStuff()
steel.doStuff()
preload preload preload