In one sentence

Separating the construction of a complex object from its representation allows the same construction process to create different representations.

Code

protocol PersonBuilder {
    func buildHead(a)
    func buildBody(a)
    func buildArm(a)
    func buildLeg(a)
}

class PersonThinBuilder: PersonBuilder {
    func buildHead(a) {
        print("Create a thin head")}func buildBody(a) {
        print("Create a lean body.")}func buildArm(a) {
        print("Create thin hands.")}func buildLeg(a) {
        print("Create thin feet")}}class PersonFatBuilder: PersonBuilder {
    func buildHead(a) {
        print("Create a fat head")}func buildBody(a) {
        print("Create a fat body.")}func buildArm(a) {
        print("Create a fat hand.")}func buildLeg(a) {
        print("Create fat feet.")}}class PersonDirector {
    let pb: PersonBuilder
    
    init(_ pb: PersonBuilder) {
        self.pb = pb
    }
    
    func createPerson(a) {
        pb.buildHead()
        pb.buildBody()
        pb.buildArm()
        pb.buildLeg()
    }
}

func main(a) {
    let pb = PersonThinBuilder(a)let pd = PersonDirector(pb)
    pd.createPerson()
}
Copy the code

When to use it?

The Builder pattern is the pattern that applies when the algorithm that creates complex objects should be independent of the components of that object and their assembly methods.