Member-only story
Builder design pattern
Builder is a Creational design pattern, and as the name suggests, it is used to build objects. If we are developing complex application, usually we have to deal with complex objects. Those objects can be dependent on several sub-objects and also may require an elaborate construction process. This is where Builder Design Pattern comes to save our day.
You can even turn builder function to composable to have more elegant looking dot syntax. A most of 3rd party swift libraries, makes developer’s life easier by taking advantage of builder pattern like swiftUI.
First of all, let’s look at what the builder pattern is and what it does for us. Creating simple objects is easy. For example, let’s consider a user object with only one property. 📖
// Defination
final class User: Identifiable {
var username: UUID
init(username: UUID) {
self.username = username
}
}
// Example Usage
User(username: UUID())
As you can see, we can create and use it quite simply. What if this class was a car object and branched out to its subclasses?
// Definations
final class Car {
var engine: Engine
var wheels: [Wheel]
var body: Body
init(engine: Engine, wheels: [Wheel], body: Body) {
self.engine = engine
self.wheels = wheels
self.body = body
}
}
final class Engine {…