The Power of Builder Design Pattern: How to Create Complex Objects with Ease

7 min read

The Builder Design Pattern is one of the most widely used patterns in software engineering. It is a creational pattern that allows you to separate the construction of complex objects from their representation.

The main idea behind the Builder Design Pattern is to create a separate class (the Builder) that is responsible for creating complex objects. The client code then interacts with the Builder to build the desired object. The Builder uses a step-by-step approach to build the object, and each step can be customized to fit the specific needs of the client.

📣 NoteI'll be discussing the examples in Python and C++. But you can apply the concept in any language supporting OOPS.

Problem with traditional approach

🤯 The Builder Pattern solves a very specific problem: Telescoping Constructors. To understand it, let us suppose we have the following constructor definitions for class Vehicle

1public Car(int id, String name) 2{ 3 this(id, name, 0, 0); 4} 5 6public Car(int id, String name, int number_of_tyres) 7{ 8 this(id, name, number_of_tyres, 0); 9}

🧐 This might not look like an issue at the earlier stages but if you have eight optional parameters and you want to represent every useful combination, you'll need 256 constructors. This would be very cumbersome and would result in a lot of boilerplate code.

Let's look at an example to see how the Builder Design Pattern works in practice.

Builder Design Pattern Participants

First, let's look at various participants of builder design pattern:

  • Product : First, we create the product's blueprint or interface, which will define the steps required to build the product. This interface can be implemented by different classes to produce different products.

  • Concrete Builder : Next, we create a concrete builder class that implements the product's interface and provides a method for each step required to build the product.

    The concrete builder class also has a method to return the final product.

  • Director : Finally, we create a director class that will use the concrete builder to build the product. The director class is responsible for invoking the concrete builder's methods in the correct order to produce the final product.

Builder design pattern Diagrams

Let's see through diagrams how builder design pattern looks or works. Imagine we're building the same car as above. The car has many attributes, such as the engine type, the number of doors, and the color.

Sequence diagram

Below are the steps required to build a car,

we can use different concrete builders to create different types of cars with different attributes.

Builder Design pattern Sequence Diagram

Below is the source code for above sequnce diagram in PlantUML:

1@startuml 2title Car Building Sequence Diagram 3 4actor Client 5 6Client -> CarDirector: create director 7Client -> AudiCarBuilder: create audi builder 8CarDirector -> CarDirector: set builder to audi builder 9Client -> CarDirector: build car 10CarDirector -> AudiCarBuilder: add engine 11AudiCarBuilder -> Car: set engine 12CarDirector -> AudiCarBuilder: add doors 13AudiCarBuilder -> Car: set doors 14CarDirector -> AudiCarBuilder: paint car 15AudiCarBuilder -> Car: paint 16CarDirector -> AudiCarBuilder: get car 17AudiCarBuilder -> Car: return car 18CarDirector -> Client: return car 19@enduml

Class Diagrams

To give you a snapshot, this is how our class skeletons would look like:

Builder Design pattern Class Diagram

In plantUML, it looks as:

1@startuml 2 3class Car { 4    - engine_type: str 5    - num_doors: int 6    - color: str 7    + set_engine(engine_type: str): void 8    + set_doors(num_doors: int): void 9    + paint(color: str): void 10} 11 12class AudiCarBuilder { 13    - car: Car 14    + AudiCarBuilder() 15    + add_engine(engine_type: str): void 16    + add_doors(num_doors: int): void 17    + paint(color: str): void 18    + get_car(): Car 19} 20 21class CarDirector { 22  - builder: ICarBuilder 23  + CarDirector(audiCarBuilder: ICarBuilder) 24  + build_car(): Car 25} 26 27AudiCarBuilder -> Car: 1 28CarDirector -> AudiCarBuilder 29 30@enduml

Builder design pattern implementation

Step 1 Declare interface of our final product

First, let's define the product, which is Car.

1class Car: 2 def __init__(self): 3 self.engine_type = None 4 self.num_doors = None 5 self.color = None 6 7 def add_engine(self, engine_type): 8 self.car.engine_type = engine_type 9 10 def add_doors(self, num_doors): 11 self.car.num_doors = num_doors 12 13 def paint(self, color): 14 self.car.color = color

Our Final product Car has engine type, the number of doors, and the color.

Step 2. Define the Builder class to implement each build step

Next step is to define the concrete builder class that implements the method for each step required to build the above product.

Remember, we also need to define a method to return the final product.

1class AudiCarBuilder: 2 def __init__(self): 3 self.car = Car() 4 5 def add_engine(self, engine_type): 6 self.car.set_engine(engine_type) 7 8 def add_doors(self, num_doors): 9 self.car.set_doors(num_doors) 10 11 def paint(self, color): 12 self.car.paint( = )color) 13 14 def get_car(self): 15 return self.car

Apart from defining various methods to build our final product, we also define the method to return it through function get_car().

Step 3.

Lastly, create a director class to build the final product.

Remember to invoke each construction step/method in the correct order to produce the final product. In our example is to first install the engine before attaching doors or starting painting. :happy:

1class CarDirector: 2 def __init__(self, builder): 3 self.builder = builder 4 5 def build_car(self): 6 self.builder.add_engine("V8") 7 self.builder.add_doors(4) 8 self.builder.paint("Red") 9 return self.builder.get_car()

Our Builder implementation is now complete. :slightly_smiling_face:

Let's use it in our code base. It's too easy now to use.

1builder = AudiCarBuilder() 2director = CarDirector(builder) 3car = director.build_car() 4 5print(f"Engine type: {car.engine_type}") 6print(f"Number of doors: {car.num_doors}") 7print(f"Color: {car.color}")

How builder pattern helped us

By using the Builder pattern, we can create different concrete builders to build different types of cars with different attributes.

We can also modify the steps required to build a car without modifying the Car class itself, making our code more flexible and easier to maintain.

Complete implementation in C++

Now, I feel it must be easy for you to understand how builder pattern can be written in C++ also. Still, for your reference I'm giving the source code here. :slightly_smiling_face:

1#include <iostream> 2#include <string> 3 4class Car { 5private: 6 std::string engine_type; 7 int num_doors; 8 std::string color; 9public: 10 void set_engine(std::string engine_type) { 11 this->engine_type = engine_type; 12 } 13 void set_doors(int num_doors) { 14 this->num_doors = num_doors; 15 } 16 void paint(std::string color) { 17 this->color = color; 18 } 19 void display() { 20 std::cout << "Car with " << engine_type << " engine, " << num_doors << " doors, and " << color << " color." << std::endl; 21 } 22}; 23 24class ICarBuilder { 25public: 26 virtual void add_engine(std::string engine_type) = 0; 27 virtual void add_doors(int num_doors) = 0; 28 virtual void paint(std::string color) = 0; 29 virtual Car get_car() = 0; 30}; 31 32class AudiCarBuilder : public ICarBuilder { 33private: 34 Car car; 35public: 36 void add_engine(std::string engine_type) { 37 car.set_engine(engine_type); 38 } 39 void add_doors(int num_doors) { 40 car.set_doors(num_doors); 41 } 42 void paint(std::string color) { 43 car.paint(color); 44 } 45 Car get_car() { 46 return car; 47 } 48}; 49 50class CarDirector { 51private: 52 ICarBuilder* builder; 53public: 54 CarDirector(ICarBuilder* builder) { 55 this->builder = builder; 56 } 57 void build_car() { 58 builder->add_engine("V6"); 59 builder->add_doors(4); 60 builder->paint("Red"); 61 } 62}; 63 64int main() { 65 AudiCarBuilder audiBuilder; 66 CarDirector director(&audiBuilder); 67 director.build_car(); 68 Car audiCar = audiBuilder.get_car(); 69 std::cout << "Audi car: "; 70 audiCar.display(); 71 return 0; 72}

💡 Remember, same way you can also add another car builder, say FordCarBuilder

Conclusion

In conclusion, the Builder pattern is a powerful design pattern that can help us create complex objects with many attributes in a more organized and maintainable way. By separating the construction of an object from its representation, we can create different types of objects with different attributes using the same building process.