Open In App

Builder Method – Python Design Patterns

Last Updated : 06 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Builder Method is a Creation Design Pattern which aims to “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” It allows you to construct complex objects step by step. Here using the same construction code, we can produce different types and representations of the object easily.
It is basically designed to provide flexibility to the solutions to various object creation problems in object-oriented programming.
 

UML Diagram of Builder Design Pattern


 

Builder-method-python-design-pattern

Builder-method


 

Problem without using the Builder Method:


Imagine you want to join one of the elite batches of GeeksforGeeks. So, you will go there and ask about the Fee structure, timings available, and batches about the course you want to join. After looking at the system, they will tell you about the courses, their Fee structures, timings available and batches. That’s it! (No! we are not done yet because we are good developers).
Our main purpose is to design the system flexible, reliable, organized and lubricative. what Unexperienced developers will do is that they will create a separate and unique class for each and every course provided by GeeksforGeeks. Then they will create separate object instantiation for each and every class although which is not required every time. The main problem will arise when GeeksforGeeks will start new courses and developers have to add new classes as well because their code is not much flexible.
 

problem-builder-method

problem-builder-Method


Note: Following code is written without using the Builder Method.
 

Python
# concrete course
class DSA():

    """Class for Data Structures and Algorithms"""

    def Fee(self):
        self.fee = 8000

    def available_batches(self):
        self.batches = 5

    def __str__(self):
        return "DSA"

# concrete course
class SDE():

    """Class for Software development Engineer"""

    def Fee(self):
        self.fee = 10000

    def available_batches(self):
        self.batches = 4

    def __str__(self):
        return "SDE"

# concrete course
class STL():

    """class for Standard Template Library of C++"""

    def Fee(self):
        self.fee = 5000

    def available_batches(self):
        self.batches = 7

    def __str__(self):
        return "STL"


# main method
if __name__ == "__main__":

    sde = SDE()   # object for SDE
    dsa = DSA()   # object for DSA
    stl = STL()   # object for STL

    print(f'Name of Course: {sde} and its Fee: {sde.fee}')
    print(f'Name of Course: {stl} and its Fee: {stl.fee}')
    print(f'Name of Course: {dsa} and its Fee: {dsa.fee}')

Solution by Builder Method:

Our final end product should be any course from GeeksforGeeks. It might be either SDE, STL or DSA. We have to go through many steps before choosing a particular course such as finding details about the courses, syllabus, fee structure, timings, and batches. Here using the same process we can select different courses available at GeeksforGeeks. That’s the benefit of using the builder Pattern.
 

solution-Builder-Method

solution-Builder-Method


 

Python
# Abstract course
class Course:

    def __init__(self):
        self.Fee()
        self.available_batches()

    def Fee(self):
        raise NotImplementedError

    def available_batches(self):
        raise NotImplementedError

    def __repr__(self):
        return 'Fee : {0.fee} | Batches Available : {0.batches}'.format(self)

# concrete course
class DSA(Course):

    """Class for Data Structures and Algorithms"""

    def Fee(self):
        self.fee = 8000

    def available_batches(self):
        self.batches = 5

    def __str__(self):
        return "DSA"

# concrete course
class SDE(Course):

    """Class for Software Development Engineer"""

    def Fee(self):
        self.fee = 10000

    def available_batches(self):
        self.batches = 4

    def __str__(self):
        return "SDE"

# concrete course
class STL(Course):

    """Class for Standard Template Library"""

    def Fee(self):
        self.fee = 5000

    def available_batches(self):
        self.batches = 7

    def __str__(self):
        return "STL"

# Complex Course
class ComplexCourse:

    def __repr__(self):
        return 'Fee : {0.fee} | available_batches: {0.batches}'.format(self)

# Complex course
class Complexcourse(ComplexCourse):

    def Fee(self):
        self.fee = 7000

    def available_batches(self):
        self.batches = 6

# construct course
def construct_course(cls):

    course = cls()
    course.Fee()
    course.available_batches()

    return course    # return the course object

# main method
if __name__ == "__main__":

    dsa = DSA()  # object for DSA course
    sde = SDE()  # object for SDE course
    stl = STL()  # object for STL course

    complex_course = construct_course(Complexcourse)
    print(complex_course)

General Class Diagram for Builder Pattern Method:

General class diagram for builder method

General class diagram for builder method

Advantages of using Builder Method:

  1. Reusability: While making the various representations of the products, we can use the same construction code for other representations as well.
  2. Single Responsibility Principle: We can separate out both the business logic as well as the complex construction code from each other.
  3. Construction of the object: Here we construct our object step by step, defer construction steps or run steps recursively.

Disadvantages of using Builder method:

  1. Code complexity increases: The complexity of our code increases, because the builder pattern requires creating multiple new classes.
  2. Mutability: It requires the builder class to be mutable
  3. Initialization: Data members of the class are not guaranteed to be initialized.

Applicability:

  1. Constructing Complex objects : The Builder Method allows you to construct the products step-by-step. Even, we can defer the execution of some steps without breaking the final product. To create an object tree, it is handy to call the steps recursively.It prevents the client code from fetching the incomplete data because it doesn’t allow the exposing of an unfinished object.
  2. Differ by Representations: The Builder pattern is applicable when construction of various representations of the product involves similar steps that differ only in the details. The base builder interface is used to define all the construction steps while these steps are implemented by concrete builders.

  
Further read: Builder Design method in C++
 



Previous Article
Next Article

Similar Reads

Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java
Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly useful when dealing with a complex object with ma
8 min read
Builder Pattern | C++ Design Patterns
The builder pattern is defined as a creational design pattern that separates the construction of a complex object from its representation, allowing us to create different representations of an object using the same construction process. It's beneficial when an object has many optional properties or configurations. The logic behind the Builder Patte
6 min read
Difference Between Architectural Style, Architectural Patterns and Design Patterns
Many software professionals think that architectural styles and patterns are the same. Sadly, some of the software developers don’t understand the difference between architectural patterns and design patterns. In this article, we're going to summarize the differences between them. According to MSDN, architectural styles and patterns are the same th
7 min read
Connectivity and Composition Patterns | Design Patterns for Cloud Native Applications
In cloud-native applications, the architectural design becomes a critical aspect, defining the success of the entire solution. Connectivity and composition patterns are fundamental design principles that dictate how different components within a cloud-native application communicate and collaborate. Let's delve deeper into the significance of these
9 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Builder Method | JavaScript Design Pattern
The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pattern in JavaScript Design Pattern Example without
9 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Builder Design Pattern
The Builder Design Pattern is a creational pattern used in software design to construct a complex object step by step. It allows the construction of a product in a step-by-step fashion, where the construction process can vary based on the type of product being built. The pattern separates the construction of a complex object from its representation
7 min read