Junior — Middle
What is the main difference between Builder and Factory patterns in object-oriented programming?
sobes.tech AI
Answer from AI
The main difference between the Builder and Factory patterns lies in their purpose and the process of object creation.
-
Factory — is a pattern responsible for creating objects of a certain family or type. It hides the logic of selecting a specific class for creation and returns a ready-made object. It is usually used when there is a need to create objects with different implementations but with the same interface.
-
Builder — is a pattern that allows step-by-step creation of a complex object, separating the construction process from the presentation. It is useful when an object consists of many parts and configurations, and flexible management of the assembly process is required.
Example:
- Factory creates different types of cars (sedan, SUV) on request.
- Builder allows assembling a car from parts: engine, wheels, body, options, step by step.
// Factory
protocol Car { func drive() }
class Sedan: Car { func drive() { print("Driving sedan") } }
class SUV: Car { func drive() { print("Driving SUV") } }
class CarFactory {
static func createCar(type: String) -> Car? {
switch type {
case "sedan": return Sedan()
case "suv": return SUV()
default: return nil
}
}
}
// Builder
class CarBuilder {
private var engine: String = ""
private var wheels: Int = 0
func setEngine(_ engine: String) -> CarBuilder {
self.engine = engine
return self
}
func setWheels(_ count: Int) -> CarBuilder {
self.wheels = count
return self
}
func build() -> Car {
// Return an object with the specified parameters
return CustomCar(engine: engine, wheels: wheels)
}
}
class CustomCar: Car {
let engine: String
let wheels: Int
init(engine: String, wheels: Int) {
self.engine = engine
self.wheels = wheels
}
func drive() {
print("Driving car with engine: \(engine) and wheels: \(wheels)")
}
}