Skip to content

Instantly share code, notes, and snippets.

@abadikaka
Last active May 13, 2020 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abadikaka/da006056c8d0c4319d05907c866b5e1b to your computer and use it in GitHub Desktop.
Save abadikaka/da006056c8d0c4319d05907c866b5e1b to your computer and use it in GitHub Desktop.
Builder Pattern Constructor way
// This is the base Car class that has all of the foundation materials to make a Car
class Car {
let doors: Door
let wheel: Wheel
let engine: Engine
let color: Color
func buildCar() -> Car
}
// This is the subclass of Car which is a SportCar that has a private initializer
// Only bake the Car with the builder using a static function, however you can omit the static one and immediate using the constructor as well (your preference)
final class SportCar: Car {
private init(builder: SportCarBuilder) {
let door = Door(2)
let engine = Engine(V85000)
let wheel = builder.wheel
let color = builder.color
super.init(doors: door, engine: engine, wheel: wheel, color: color)
}
static func make(with builder: SportCarBuilder) -> SportCar {
return SportCar(builder: builder)
}
}
// This is the SportCarBuilder that just need color and wheel because the engine and the door will be automatically adjusted on the class who will use this by default
struct SportCarBuilder {
let color: Color
let wheel: Wheel
}
// This is the factory class for creating the necessary car on the company
// User will just need this class to retrieve the final product they need
final class CarFactory {
func sportCar(with builder: SportCarBuilder) -> SportCar {
return SportCar.make(builder: builder)
}
func truckCar(with builder: TruckCarBuilder) -> TruckCar {
return TruckCar.make(builder: builder)
}
func SUVCar(with builder: SUVCarBuilder) -> SUVCar {
return SUVCar.make(builder: builder)
}
func familyCar(with builder: FamilyCarBuilder) -> FamilyCar {
return FamilyCar.make(builder: builder)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment