Swift World: Design Patterns - Builder

Normally, while building a car, we build every part first and then assemble them up. As customers, we don’t need to know how to produce every component. It’s the producer’s job to produce a functional car according to our requirements.

Do you remember our factory in Factory Method Pattern ?

protocol Factory {
    func produce() -> Car
}

It’s too simple to describe the real world. Let’s enhance it.

protocol Factory {
    func produceWheel()
    func produceEngine()
    func produceChassis()
}

We still need concrete factory to produce the real car for example a sedan factory or a SUV factory.

class SedanFactory: Factory {
    func produceWheel() {
        print("produce wheel for sedan")
    }
    func produceEngine() {
        print("produce engine for sedan")
    }
    func produceChassis() {
        print("produce chassis for sedan")
    }
}
class SUVFactory: Factory {
    func produceWheel() {
        print("produce wheel for SUV")
    }
    func produceEngine() {
        print("produce engine for SUV")
    }
    func produceChassis() {
        print("produce chassis for SUV")
    }
}

Now, we can produce sedan and SUV. But as customers, we don’t give order to the factory directly. Let’s assume there is ‘director’ between customers and automaker. The director gets orders from customers and direct factories to produce cars.

class Director {
    var factory: Factory

    init(factory: Factory) {
        self.factory = factory
    }

    func produce() {
        factory.produceWheel()
        factory.produceEngine()
        factory.produceChassis()
    }
}

Let’s start to produce cars.

let sedanFactory = SedanFactory()
let suvFactory = SUVFactory()

let sedanDirector = Director(factory: sedanFactory)
sedanDirector.produce()
let suvDirector = Director(factory: suvFactory)
suvDirector.produce()

So the structure becomes to the following.

《Swift World: Design Patterns - Builder》

Thanks for your time.

Please enable JavaScript to view the <a href=”https://disqus.com/?ref_noscript”>comments powered by Disqus.</a>

    原文作者:算法小白
    原文地址: https://juejin.im/entry/58c3d9a5da2f6056096b3459
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞