Builder Pattern Introduction in Python

Builder Pattern Introduction

Welcome back! So far, we've covered various creational design patterns like the Singleton Pattern, Factory Method Pattern, and Abstract Factory Pattern. These patterns have helped you control and simplify object creation in your programs. Today, we are delving into another powerful creational pattern — the Builder Pattern. This pattern allows you to construct complex objects step by step, making the creation process more manageable and modular.

Defining the Builder Pattern

The Builder Pattern is a design pattern that provides a way to construct complex objects step by step. It decouples the construction process from the representation, allowing the same construction process to create different representations. This pattern includes several key components: the product (the complex object to be created), the builder interface (specifying the construction steps), one or more concrete builders (implementing the construction steps for different representations), and a director (managing the construction process).

Implementing a Concrete Builder and Using a Director

Let's break down the implementation of the Builder Pattern in Python with an example. For this example, we will create different types of houses using various builders.

Defining the House Class

First, we define the House class, which will be our complex object:

class House:
    def __init__(self):
        self.foundation = None
        self.structure = None
        self.roof = None

    def set_foundation(self, foundation):
        self.foundation = foundation

    def set_structure(self, structure):
        self.structure = structure

    def set_roof(self, roof):
        self.roof = roof

    def show_house(self):
        print(f"House with {self.foundation}, {self.structure}, and {self.roof}.")

In this class, the House object has three main parts: the foundation, the structure, and the roof. We also have methods to set these parts and a method to display the house.

Creating the Builder Interface

Next, we define the HouseBuilder interface:

from abc import ABC, abstractmethod

class HouseBuilder(ABC):
    @abstractmethod
    def build_foundation(self):
        pass

    @abstractmethod
    def build_structure(self):
        pass

    @abstractmethod
    def build_roof(self):
        pass

    @abstractmethod
    def get_house(self):
        pass

This interface specifies the methods that any concrete builder must implement. The build_foundation, build_structure, and build_roof methods represent the steps to construct a house.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal