Builder design pattern in Swift

Chanakya Hirpara
3 min readJun 17, 2023

In Swift, the Builder design pattern is a creational pattern that provides a structured way to create complex objects step by step. It promotes readable and maintainable code by separating the construction logic from the object’s representation. In this post, we’ll dive into the Builder design pattern and explore its implementation with a practical example.

  1. What is the Builder Design Pattern? The Builder design pattern separates the construction of an object from its representation, allowing us to create complex objects by using a step-by-step approach. It provides a clean and fluent interface for setting various attributes of an object and abstracts away the construction details.
  2. Implementation of the Builder Design Pattern: Realtime Example Let’s consider a scenario where we need to build a Pizza object with different toppings, crust types, and sizes. Here's an example of how the Builder design pattern can be implemented:
class Pizza { 
var toppings: [String]
var crust: String
var size: String

init(toppings: [String], crust: String, size: String) {
self.toppings = toppings
self.crust = crust
self.size = size
}
}

class PizzaBuilder {
private var toppings: [String] = []
private var crust: String = ""
private var size: String = ""

func addToppings(_ toppings: [String]) -> PizzaBuilder {
self.toppings.append(contentsOf: toppings)
return self
}

func setCrust(_ crust: String) -> PizzaBuilder {
self.crust = crust
return self
}

func setSize(_ size: String) -> PizzaBuilder {
self.size = size
return self
}

func build() -> Pizza {
return Pizza(toppings: toppings, crust: crust, size: size)
}
}

let pizza = PizzaBuilder()
.addToppings(["Pepperoni", "Mushrooms", "Onions"])
.setCrust("Thin Crust")
.setSize("Large")
.build()

In this example, we have a Pizza class representing the final product, and a PizzaBuilder class responsible for constructing the Pizza object. The PizzaBuilder class provides methods for setting different attributes of the Pizza object and returns itself (PizzaBuilder) to enable method chaining.

By invoking methods on the PizzaBuilder instance, we can add toppings, set the crust type, and define the size of the pizza. Finally, the build method creates a Pizza object using the accumulated attributes and returns the finalized pizza.

  1. Advantages of the Builder Design Pattern
  • Readable and Maintainable Code: The Builder pattern enhances code readability by providing a clear and fluent API for object creation. It also abstracts away the complex construction logic, making the code easier to maintain and modify.
  • Flexibility in Object Creation: With the Builder pattern, you can create different variations of an object by using various combinations of attributes, all managed by the builder. This flexibility allows for easy customization and adaptation as per specific requirements.
  • Separation of Concerns: The Builder pattern separates the construction process from the representation of the object, ensuring that the construction logic remains isolated and reusable. It promotes the Single Responsibility Principle (SRP) and adheres to the principle of encapsulation.

When to Use the Builder Design Pattern The Builder pattern is useful in scenarios where:

  • The creation of an object involves multiple steps or parameters.
  • The object’s construction logic is complex and needs to be abstracted.
  • Different combinations of attributes need to be supported.
  • Readability and maintainability of the code are crucial.

Conclusion The Builder design pattern is a powerful tool in Swift for constructing complex objects using a step-by-step approach. By separating the construction logic from the object’s representation, it promotes code readability, maintainability, and flexibility.

In this post, we explored the Builder design pattern and demonstrated its implementation with a realtime example of building a Pizza object. By leveraging the Builder pattern, we can easily create pizzas with different toppings, crust types, and sizes while maintaining a clean and structured codebase.

Consider using the Builder pattern in your Swift projects when you need to construct complex objects, enhance code readability, and enable easy customization.

Happy building with the Builder pattern in Swift!

Please clap, follow and share if you like this post.

--

--