Explaining the Builder Design pattern

The builder design pattern is a creational design pattern that provides a way to create complex objects step by step, using a single building process. This pattern separates the construction of the object from its representation, allowing the same construction process to create different representations.

In Swift, the builder design pattern is often implemented using classes and protocols. Here's an example to illustrate how this works:

// This is a protocol that defines the basic interface for a car.
// Any class that conforms to this protocol can be used as a car.
protocol Car {
  var make: String { get }
  var model: String { get }
  var year: Int { get }
  var color: String { get }
}

// This is a simple class that represents a car.
// The class conforms to the Car protocol by implementing
// the required properties.
class CarClass: Car {
  let make: String
  let model: String
  let year: Int
  let color: String

  init(make: String, model: String, year: Int, color: String) {
    self.make = make
    self.model = model
    self.year = year
    self.color = color
  }
}

// This is a builder class that constructs a car object.
// The builder has methods that allow the user to set each
// property of the car object, and a method to retrieve the
// final car object.
class CarBuilder {
  var make: String = ""
  var model: String = ""
  var year: Int = 0
  var color: String = ""

  func setMake(make: String) -> CarBuilder {
    self.make = make
    return self
  }

  func setModel(model: String) -> CarBuilder {
    self.model = model
    return self
  }

  func setYear(year: Int) -> CarBuilder {
    self.year = year
    return self
  }

  func setColor(color: String) -> CarBuilder {
    self.color = color
    return self
  }

  func build() -> Car {
    return CarClass(make: make, model: model, year: year, color: color)
  }
}

// Now we can use the CarBuilder to construct a car object.
let carBuilder = CarBuilder()

let car = carBuilder
  .setMake(make: "Toyota")
  .setModel(model: "Corolla")
  .setYear(year: 2020)
  .setColor(color: "Red")
  .build()

// The car object can now be used like any other Car object.
print("Car make: \(car.make)")
print("Car model: \(car.model)")
print("Car year: \(car.year)")
print("Car color: \(car.color)")

In this example, we define a Car protocol that specifies the basic interface for a car object. We also define a CarClass class that conforms to the Car protocol and provides an implementation of the required properties.

We then define a CarBuilder class that has methods for setting each property of a Car object. The CarBuilder also has a build() method that constructs and returns a Car object using the current property values.

Previous
Previous

Explaining the Singleton Design Pattern

Next
Next

Explaining the concept of Abstraction