Software Development
Design Patterns
Builder Pattern
Factory Pattern
Programming Concepts

What is the difference between Builder Design pattern and Factory Design pattern?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

The Builder and Factory design patterns are both creational patterns used in object-oriented design, and they aim to solve different problems related to object creation. While they share the common goal of constructing objects, the way they structure the code and manage dependencies varies significantly. Understanding their differences is crucial for applying the correct pattern based on the requirements of your software design.

Builder Design Pattern

The Builder design pattern is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing the same construction process to create different representations. This pattern is specifically beneficial when an object has multiple components and a straightforward configuration method would result in a constructor with many parameters (telescoping constructor anti-pattern).

Technical Explanation:

The Builder pattern involves at least three components:

  • Builder: Provides an interface for adding parts to the object being constructed.
  • Concrete Builder: Implements the builder interface and keeps track of the representation it creates. It provides an interface for retrieving the product.
  • Director: Constructs an object using the Builder interface.

Example:

Consider a scenario where we need to construct a customizable Car object. A car can have various features and specifications like engine type, wheel size, color, and accessories.

python
1class Car:
2    def __init__(self):
3        self.features = {}
4
5    def add_feature(self, key, value):
6        self.features[key] = value
7
8class CarBuilder:
9    def __init__(self):
10        self.car = Car()
11
12    def set_engine(self, engine_type):
13        self.car.add_feature("engine", engine_type)
14        return self
15
16    def set_wheels(self, size):
17        self.car.add_feature("wheels", size)
18        return self
19
20    def set_color(self, color):
21        self.car.add_feature("color", color)
22        return self
23
24    def build(self):
25        return self.car
26
27# Usage:
28builder = CarBuilder()
29car = builder.set_engine("V8").set_wheels(17).set_color("red").build()

In this example, the CarBuilder allows the construction of a Car object step-by-step, setting one feature at a time. This flexibility ensures that the client can decide the specific configuration of the product.

Factory Design Pattern

The Factory design pattern is used to create objects without specifying the exact class of object that will be created. The pattern encapsulates object creation by allowing clients to request objects by passing a type or other identifying information, shifting the responsibility for the instantiation of the object to a separate "factory" object.

Technical Explanation:

The Factory pattern can be implemented in several ways, including:

  • Simple Factory: Not a formal design pattern, more of a programming idiom. It typically consists of a static method which creates objects based on input parameters.
  • Factory Method: Defines an interface for creating an object, but lets subclasses decide which class to instantiate.
  • Abstract Factory: Provides an interface for creating families of related or dependent objects without specifying concrete classes.

Example:

python
1class Dog:
2    def speak(self):
3        return "Woof!"
4
5class Cat:
6    def speak(self):
7        return "Meow!"
8
9def get_pet(pet_type):
10    pets = {
11        "dog": Dog,
12        "cat": Cat,
13    }
14    return pets[pet_type]()
15
16# Usage:
17pet = get_pet("dog")
18print(pet.speak())  # Output: Woof!

In this example, the get_pet function acts as a simple factory method that encapsulates the instantiation logic and returns a new instance based on the input.

Comparison Table

AspectBuilder PatternFactory Pattern
PurposeTo construct a complex object step by step.To create an instance of a class with a common interface.
ImplementationInvolves a Director, Builder, and ConcreteBuilders.Can be implemented via Factory Method, Abstract Factory, or Simple Factory.
FlexibilityHigh, as the client can specify each step and part.High, as factory can hide the instantiation logic and simplify object creation.
Control Over StepsThe construction is controlled by the client via the builder.The instantiation is hidden inside the factory and cannot be altered by the client.

In conclusion, while both the Builder and Factory patterns help in object creation, the Builder pattern provides more control over the construction process and is suited for situations where the product configuration needs multiple steps. The Factory pattern, meanwhile, is advantageous when object creation should be independent of system logic and multiple similar objects need instantiation that share a common goal.


Course illustration
Course illustration

All Rights Reserved.