Swift with Furkan

What is the Builder Pattern? How to use it in Swift?

builder pattern

The Builder Pattern is a creational design pattern that separates the construction of a complex object from its representation, so that the same construction process can create different representations. The builder pattern is often used when the algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled.

The builder pattern is used to create complex objects by specifying the type and content of each object in a step-by-step. The final step creates the object.

Here is an example of how to use the builder pattern in Swift:

[swift]class Builder {
var product = Product()

func setPartA() {
product.parts.append("PartA1")
}

func setPartB() {
product.parts.append("PartB1")
}

func setPartC() {
product.parts.append("PartC1")
}
}

class Product {
var parts = [String]()

func listParts() -> String {
return "Product parts: " + parts.joined(separator: ", ") + "\n"
}
}

// Director
class Director {
var builder: Builder

init(builder: Builder) {
self.builder = builder
}

func buildMinimalViableProduct() {
builder.setPartA()
}

func buildFullFeaturedProduct() {
builder.setPartA()
builder.setPartB()
builder.setPartC()
}
}

// Client
let builder = Builder()
let director = Director(builder: builder)

print("Standard basic product:")
director.buildMinimalViableProduct()
print(builder.product.listParts())

print("Standard full featured product:")
director.buildFullFeaturedProduct()
print(builder.product.listParts())
[/swift]

In this example, the Builder class defines the construction steps for creating a Product object. The Director class controls the construction process by calling the suitable steps in the Builder. The Client code creates a Builder object and a Director object, and then calls the Director to construct the desired product. The final step creates the Product object.

Exit mobile version