Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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