Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Builder Design Pattern

The Builder pattern is a creational design pattern that lets you construct complex objects step by step. It enables you to produce different types and representations of an object using the same construction code.

7 min readNov 4, 2024

--

Complexity: ⭐️⭐️★
Popularity: ⭐️⭐️⭐️

The Problem Builder Solves

Imagine you’re creating a complex object that requires laborious, step-by-step initialization of many fields and nested objects. Let’s use a smartphone configuration system as an example.

A basic smartphone might need: a processor, memory, storage, screen, battery, camera… But if a customer wants additional features like: dual cameras, extended battery, extra storage, 5G capability, wireless charging, biometric security(seems like wants an iPhone right? 📱)

The simple solution is to extend base SmartPhone class and create a set of subclasses to cover all combinations. This approach has a significant drawback which is creating a subclass for each possible combination of features would lead to an enormous number of classes. Alright, what if we create a single constructor with all possible parameters? Yeah, this approach eliminates subclasses but it would be unwieldy and confusing.

Press enter or click to view image in full size
The initializer with lots of parameters has its downsides: not all the parameters are needed at all time.

Most of these parameters would be unused in any given instance, making the code messy and error-prone.

The Builder Solution

The Builder pattern suggests extracting the object construction code out of its own class and moving it to separate objects called builders.

Press enter or click to view image in full size
Builder pattern lets you construct complex object step-by-step. The Builder doesn't allow the other object to access to the product while it's being built.

To create an object, you invoke a series of steps on a builder object, calling only the steps you need. Some steps may require different implementations, so you can create multiple builder classes that implement the same set of construction steps in various ways.

However, this works only if the client code interacts with the builders through a shared interface.

The Director

Get Ahmet Tarik DÖNER’s stories in your inbox

Join Medium for free to get updates from this writer.

You can take this approach further by introducing a Director class. The Director defines the order in which to execute the building steps, while the builder implements each step. The Director isn’t always necessary, but it can be helpful for reusing certain construction routines and concealing the construction details from the client code. With a Director, the client only needs to associate a builder with the Director, trigger the construction process, and obtain the result from the builder.

The Builder Structure

Press enter or click to view image in full size
Structure of Builder

Domain of Applicability

  • To avoid telescoping constructors: If you have a constructor with numerous optional parameters, the Builder pattern allows you to build objects step-by-step, only using the steps necessary for your configuration.
  • To create different representations of an object: This pattern is useful when building various representations of an object involves similar steps that differ only in specific details.

How does the Builder Implements:

  1. Define common construction steps for building all available representations of the product.
  2. Declare these steps in a base builder interface.
  3. Create concrete builder classes for each product representation, implementing the steps required for each. Be sure to add a method for retrieving the final product. This retrieval method is usually not part of the base builder interface, as different builders may return different types.
  4. Consider creating a Director class if there is a need to organize and control the construction sequence.
  5. The client creates both the builder and the Director. Before starting construction, the client assigns the builder to the Director, often via parameters in the Director’s constructor.
  6. Retrieve the constructed object: If all products follow a common interface, the Director can return the result directly; otherwise, the client should get the final product from the builder.

Conceptual Example

import Cocoa

/// Builder interface specifies methods for creating the different parts of the Product object.
protocol Builder {
func producePartA()
func producePartB()
func producePartC()
}

/// ConcreteBuilder classes follow the Builder interface and provide specific implementation
/// of the building steps. Your program may have several variations of Builders, implemented differently.
class ConcreteBuilder1: Builder {
/// A fresh builder instance should contain a blank product object, which is used in further assembly.
private var product = Product1()

func producePartA() {
product.add(part: "PartA1")
}
/// All production steps work with the same product instance.
func producePartB() {
product.add(part: "PartB1")
}

func producePartC() {
product.add(part: "PartC1")
}

func reset() {
product = Product1()
}

/// Concrete Builders are supposed to provide their own methods for retrieving results. That's because various types of builders may create
/// entirely different product that don't follow the same interface. Therefore, such methods cannot be declared in the base Builder interface.
///
/// Usually, after returning the end result to client, a builder instance is expected to be ready to start producing another product.That's why it's a usual practice
/// to call the reset method at the end of the 'getProduct' method body. However, this behavior is not mandatory.
/// You can make your builders wait for an explicit reset call from the client code before disposing the previous result.
func retrieveProduct() -> Product1 {
let result = self.product
reset()

return result
}
}

/// Director is only responsible for executing the building steps in a particular sequence. It is helpful
/// when producing products according to specific order or configuration. Strictly speaking, the Director class is optional
/// , since the client can control builders directly.
class Director {
private var builder: Builder?

/// Director works with any builder instance that the client code passes to it.
/// This way the client code may alter the final type of newly assembled product.
func update(builder: Builder) {
self.builder = builder
}

func buildMinimalViableProduct() {
builder?.producePartA()
}

func buildFullFeaturedProduct() {
builder?.producePartA()
builder?.producePartB()
builder?.producePartC()
}
}

/// Make sense to use Builder pattern only when your products are quite complex and require extensive configurations.
/// Unlike in other creational patterns, different concrete builders can produce unrelated products. In other words, results of
/// various builders may not always follows the same interface.
class Product1 {
private var parts = [String]()

func add(part: String) {
self.parts.append(part)
}

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


class Client {
static func someClientCode(director: Director) {
let builder = ConcreteBuilder1()
director.update(builder: builder)
print("Standart basic product:")
director.buildMinimalViableProduct()
print(builder.retrieveProduct().listsPart())
/// Remember, builder pattern can be used without a director class
print("Custom Product: ")
builder.producePartA()
builder.producePartC()
print(builder.retrieveProduct().listsPart())
}
}

class TestBuilderConceptual {
func test() {
let director = Director()
Client.someClientCode(director: director)
}
}
let test = TestBuilderConceptual()
test.test()

Real World Example

import Foundation

class BaseQueryBuilder<Model: DomainModel> {
typealias Predicate = (Model) -> Bool

func limit(_ limit: Int) -> BaseQueryBuilder<Model> {
return self
}

func filter(_ predicate: @escaping Predicate) -> BaseQueryBuilder<Model> {
return self
}

func fetch() -> [Model] {
preconditionFailure("Should be overridden in subclasses.")
}
}

class RealmQueryBuilder<Model: DomainModel>: BaseQueryBuilder<Model> {
fileprivate var operations = [Query]()
enum Query {
case filter(Predicate)
case limit(Int)
}

@discardableResult
override func limit(_ limit: Int) -> BaseQueryBuilder<Model> {
operations.append(Query.limit(limit))
return self
}

@discardableResult
override func filter(_ predicate: @escaping Predicate) -> BaseQueryBuilder<Model> {
operations.append(Query.filter(predicate))
return self
}

override func fetch() -> [Model] {
print("RealmQueryBuilder: Initializing RealmDataProvider with \(operations.count) operations")
return RealmProvider().fetch(operations)
}
}

class CoreDataQueryBuilder<Model: DomainModel>: BaseQueryBuilder<Model> {
enum Query {
case filter(Predicate)
case limit(Int)
case includesPropertyValues(Bool)
/// ...
}

fileprivate var operations = [Query]()

override func limit(_ limit: Int) -> CoreDataQueryBuilder<Model> {
operations.append(Query.limit(limit))
return self
}

override func filter(_ predicate: @escaping Predicate) -> CoreDataQueryBuilder<Model> {
operations.append(Query.filter(predicate))
return self
}

func includesPropertyValues(_ toggle: Bool) -> CoreDataQueryBuilder<Model> {
operations.append(Query.includesPropertyValues(toggle))
return self
}

override func fetch() -> [Model] {
print("CoreDataQueryBuilder: Initializing CoreDataProvider with \(operations.count) operations.")
return CoreDataProvider().fetch(operations)
}
}

class CoreDataProvider {

func fetch<Model: DomainModel>(_ operations: [CoreDataQueryBuilder<Model>.Query]) -> [Model] {

/// Create a NSFetchRequest

print("CoreDataProvider: Retrieving data from CoreData...")

for item in operations {
switch item {
case .filter(_):
print("CoreDataProvider: executing the 'filter' operation.")
/// Set a 'predicate' for a NSFetchRequest.
break
case .limit(_):
print("CoreDataProvider: executing the 'limit' operation.")
/// Set a 'fetchLimit' for a NSFetchRequest.
break
case .includesPropertyValues(_):
print("CoreDataProvider: executing the 'includesPropertyValues' operation.")
/// Set an 'includesPropertyValues' for a NSFetchRequest.
break
}
}

/// Execute a NSFetchRequest and return results.
return []
}
}

class RealmProvider {
func fetch<Model: DomainModel>(_ operations: [RealmQueryBuilder<Model>.Query]) -> [Model] {
print("RealmProvider: Retrieving data from Realm...")
for item in operations {
switch item {
case .filter(_):
print("RealmProvider: executing the 'filter' operation.")
/// Use Realm instance to filter results.
break
case .limit(_):
print("RealmProvider: executing the 'limit' operation.")
/// Use Realm instance to limit results.
break
}
}
/// Return results from Realm
return []
}
}

protocol DomainModel {
/// The protocol groups domain models to the common interface.
}

private struct User: DomainModel {
let id: Int
let age: Int
let email: String
}

import XCTest

class BuilderRealWorld: XCTestCase {

func testBuilderRealWorld() {
print("Client: Start fetching data from Realm")
clientCode(builder: RealmQueryBuilder<User>())

print()

print("Client: Start fetching data from CoreData")
clientCode(builder: CoreDataQueryBuilder<User>())
}

fileprivate func clientCode(builder: BaseQueryBuilder<User>) {

let results = builder.filter({ $0.age < 20 })
.limit(1)
.fetch()

print("Client: I have fetched: " + String(results.count) + " records.")
}
}
let test = BuilderRealWorld()
test.testBuilderRealWorld()

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--