C/O - Builder
- Category: Creational
- Type: object
- Motivation: to avoid too many parameters in constructor method (create object with several options)
do {
let builder = CarBuilder()
let director = Manufacturer(builder)
director.makeSportCar()
builder.car.description()
/*
Car:
seats: true
engine: true
GPS: false
*/
}
class Car
{
var seats: Bool = false
var engine: Bool = false
var GPS: Bool = false
}
extension Car
{
func description()
{
print("Car:")
print("seats: \(seats)")
print("engine: \(engine)")
print("GPS: \(GPS)")
}
}
protocol Builder
{
func reset()
func addSeats()
func addEngine()
func addGPS()
}
class CarBuilder: Builder
{
var car = Car()
func reset()
{
car = Car()
}
func addSeats() {
car.seats = true
}
func addEngine() {
car.engine = true
}
func addGPS() {
car.GPS = true
}
}
class Manufacturer
{
let builder: Builder
init(_ builder: Builder)
{
self.builder = builder
}
func makeSportCar()
{
builder.addSeats()
builder.addEngine()
}
func makeSUV()
{
builder.addSeats()
builder.addEngine()
builder.addGPS()
}
}