The Wayback Machine - https://web.archive.org/web/20241122132303/https://www.geeksforgeeks.org/builder-design-pattern/
Open In App

Builder Design Pattern

Last Updated : 16 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 manner, where the construction process can change based on the type of product being built. This pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations.

builder-Design-pattern

For an in-depth understanding of the Builder pattern, the System Design Course covers the principles behind the pattern and walks you through practical implementation techniques.

Components of the Builder Design Pattern

1. Product

The Product is the complex object that the Builder pattern is responsible for constructing.

  • It may consist of multiple components or parts, and its structure can vary based on the implementation.
  • The Product is typically a class with attributes representing the different parts that the Builder constructs.

2. Builder

The Builder is an interface or an abstract class that declares the construction steps for building a complex object.

  • It typically includes methods for constructing individual parts of the product.
  • By defining an interface, the Builder allows for the creation of different concrete builders that can produce variations of the product.

3. ConcreteBuilder

ConcreteBuilder classes implement the Builder interface, providing specific implementations for building each part of the product.

  • Each ConcreteBuilder is custmized to create a specific variation of the product.
  • It keeps track of the product being constructed and provides methods for setting or constructing each part.

4. Director

The Director is responsible for managing the construction process of the complex object.

  • It collaborates with a Builder, but it doesn’t know the specific details about how each part of the object is constructed.
  • It provides a high-level interface for constructing the product and managing the steps needed to create the complex object.

5. Client

The Client is the code that initiates the construction of the complex object.

  • It creates a Builder object and passes it to the Director to initiate the construction process.
  • The Client may retrieve the final product from the Builder after construction is complete.

Steps to implement Builder Design Pattern

Below are the steps to implement Builder Design Pattern:

  1. Create the Product Class: Define the object (product) that will be built. This class contains all the fields that make up the object.
  2. Create the Builder Class: This class will have methods to set the different parts of the product. Each method returns the builder itself to allow method chaining.
  3. Add a Build Method: In the builder class, add a method called build() (or similar) that assembles the product and returns the final object.
  4. Use the Director (Optional): If needed, you can create a director class to control the building process and decide the order in which parts are constructed.
  5. Client Uses the Builder: The client will use the builder to set the desired parts step by step and call the build() method to get the final product.

Builder Design Pattern Example

Problem Statement:

You are tasked with implementing a system for building custom computers. Each computer can have different configurations based on user preferences. The goal is to provide flexibility in creating computers with varying CPUs, RAM, and storage options.

Implement the Builder design pattern to achieve this, allowing the construction of computers through a step-by-step process. Use the provided components – Product (Computer), Builder interface, ConcreteBuilder (GamingComputerBuilder), Director, and Client

UML-Class-Diagram-for-Builder-Design-Pattern

1. Product (Computer)

C++
// Product
class Computer {
 
private:
    string cpu_;
    string ram_;
    string storage_;
  
  
public:
    void setCPU(const std::string& cpu) {
        cpu_ = cpu;
    }

    void setRAM(const std::string& ram) {
        ram_ = ram;
    }

    void setStorage(const std::string& storage) {
        storage_ = storage;
    }

    void displayInfo() const {
        std::cout << "Computer Configuration:"
                  << "\nCPU: " << cpu_
                  << "\nRAM: " << ram_
                  << "\nStorage: " << storage_ << "\n\n";
    }
};

2. Builder

C++
// Builder interface
class Builder {
public:
    virtual void buildCPU() = 0;
    virtual void buildRAM() = 0;
    virtual void buildStorage() = 0;
    virtual Computer getResult() = 0;
};

3. ConcreteBuilder

C++
// ConcreteBuilder
class GamingComputerBuilder : public Builder {
private:
    Computer computer_;

public:
    void buildCPU() override {
        computer_.setCPU("Gaming CPU");
    }

    void buildRAM() override {
        computer_.setRAM("16GB DDR4");
    }

    void buildStorage() override {
        computer_.setStorage("1TB SSD");
    }

    Computer getResult() override {
        return computer_;
    }
};

4. Director

C++
// Director
class ComputerDirector {
public:
    void construct(Builder& builder) {
        builder.buildCPU();
        builder.buildRAM();
        builder.buildStorage();
    }
};

5. Client

C++
// Client
int main() {
    GamingComputerBuilder gamingBuilder;
    ComputerDirector director;

    director.construct(gamingBuilder);
    Computer gamingComputer = gamingBuilder.getResult();

    gamingComputer.displayInfo();

    return 0;
}

Complete Combined code for the above example

Below is the full combined code for the above example:

C++
#include <iostream>
#include <string>

using namespace std;

// Product
class Computer {
public:
    void setCPU(const std::string& cpu) {
        cpu_ = cpu;
    }

    void setRAM(const std::string& ram) {
        ram_ = ram;
    }

    void setStorage(const std::string& storage) {
        storage_ = storage;
    }

    void displayInfo() const {
        std::cout << "Computer Configuration:"
                  << "\nCPU: " << cpu_
                  << "\nRAM: " << ram_
                  << "\nStorage: " << storage_ << "\n\n";
    }

private:
    string cpu_;
    string ram_;
    string storage_;
};

// Builder interface
class Builder {
public:
    virtual void buildCPU() = 0;
    virtual void buildRAM() = 0;
    virtual void buildStorage() = 0;
    virtual Computer getResult() = 0;
};

// ConcreteBuilder
class GamingComputerBuilder : public Builder {
private:
    Computer computer_;

public:
    void buildCPU() override {
        computer_.setCPU("Gaming CPU");
    }

    void buildRAM() override {
        computer_.setRAM("16GB DDR4");
    }

    void buildStorage() override {
        computer_.setStorage("1TB SSD");
    }

    Computer getResult() override {
        return computer_;
    }
};

// Director
class ComputerDirector {
public:
    void construct(Builder& builder) {
        builder.buildCPU();
        builder.buildRAM();
        builder.buildStorage();
    }
};

// Client
int main() {
    GamingComputerBuilder gamingBuilder;
    ComputerDirector director;

    director.construct(gamingBuilder);
    Computer gamingComputer = gamingBuilder.getResult();

    gamingComputer.displayInfo();

    return 0;
}

Output
Computer Configuration:
CPU: Gaming CPU
RAM: 16GB DDR4
Storage: 1TB SSD

This code demonstrates the Builder design pattern where the Computer class is the product, Builder is the interface, GamingComputerBuilder is the concrete builder, ComputerDirector is the director, and the Client assembles the product using the builder and director.

When to use Builder Design Pattern?

The Builder design pattern is used when you need to create complex objects with a large number of optional components or configuration parameters. This pattern is particularly useful when an object needs to be constructed step by step, some of the scenarios where the Builder design pattern is beneficial are:

  • Complex Object Construction: When you have an object with many optional components or configurations and you want to provide a clear separation between the construction process and the actual representation of the object. 
  • Step-by-Step Construction: When the construction of an object involves a step-by-step process where different configurations or options need to be set at different stages.
  • Avoiding constructors with multiple parameters: When the number of parameters in a constructor becomes too large, and using telescoping constructors (constructors with multiple parameters) becomes unwieldy and error-prone.
  • Configurable Object Creation: When you need to create objects with different configurations or variations, and you want a more flexible and readable way to specify these configurations.
  • Common Interface for Multiple Representations: When you want to provide a common interface for constructing different representations of an object.

When not to use Builder Design Pattern?

While the Builder design pattern is beneficial in many scenarios, there are situations where it might be unnecessary. Here are some cases when you should avoid the Builder pattern:

  • Simple Object Construction:
    • If the object you are constructing has only a few simple parameters or configurations, and the construction process is straightforward, using a builder might be unnecessary.
  • Performance Concerns:
    • In performance-critical applications, the additional overhead introduced by the Builder pattern might be a concern. The extra method calls and object creations involved in the builder process could impact performance, especially if the object construction is frequent.
  • Immutable Objects with Final Fields:
    • While working with a language that supports immutable objects with final fields (e.g., Java’s final keyword), and the object’s structure is relatively simple, you might prefer using constructors with parameters or static factory methods.
  • Increased Code Complexity:
    • Introducing a builder class for every complex object can lead to an increase in code complexity.
    • If the object being constructed is simple and doesn’t benefit significantly from a step-by-step construction process, using a builder might add unnecessary complexity to the codebase.
  • Tight Coupling with Product:
    • If the builder is tightly coupled with the product it constructs, and changes to the product require corresponding modifications to the builder, it might reduce the flexibility and maintainability of the code.




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
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
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
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Mediator Design Pattern vs. Observer Design Pattern
The Mediator Design Pattern and Observer Design Pattern are both key design patterns that help manage object communication but differ in approach. The Mediator Pattern centralizes interactions, where objects communicate through a mediator, reducing dependencies. In contrast, the Observer Pattern allows objects to subscribe to changes in a subject,
5 min read
Builder Method - Python Design Patterns
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 representatio
5 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
CQRS Pattern vs. Repository Pattern in System Design
The CQRS Pattern and the Repository Pattern are architectural patterns used to handle data in software applications. CQRS focuses on separating commands (writes) and queries (reads) into different models. The Repository Pattern abstracts data access logic by creating a layer that mediates between the domain and the data source. Table of Content Wha
5 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 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
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 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
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
Difference Between Bridge Pattern and Adapter Pattern
The Bridge Pattern and the Adapter Pattern are structural design patterns in object-oriented software development that primarily target the flexibility and reusability of a design. These two patterns have different roles and are used in different scenarios to solve specific design issues. Important Topics for Bridge Pattern vs Adapter Pattern What
5 min read
Difference between Strategy pattern and Command pattern
In software design, patterns provide reusable solutions to common problems. The Strategy and Command patterns are two important behavioral design patterns. The Strategy pattern allows the selection of an algorithm at runtime. The Command pattern encapsulates a request as an object. Understanding the differences between these patterns is crucial for
6 min read
Strangler Pattern in Micro-services | System Design
The Strangler pattern is an architectural approach employed during the migration from a monolithic application to a microservices-based architecture. It derives its name from the way a vine slowly strangles a tree, gradually replacing its growth. Similarly, the Strangler pattern involves replacing parts of a monolithic application with microservice
4 min read
10 Best Python Design Pattern Books for Beginners to Advanced
Imagine you're building different types of furniture using the same basic materials (like wood, screws, and nails). Instead of starting from scratch every time, you create templates or instructions for making specific types of furniture. These templates tell you what pieces to use, how to assemble them, and how to add unique features. In software p
4 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are compatible and properly configured. In this artic
6 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects. Important Topics for the Abstr
6 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emerges as a solution to this problem, offering a way
9 min read
Proxy Pattern | C++ Design Patterns
Design Patterns are an essential part of software engineering, offering proven solutions to common problems encountered during software development. One such pattern is the Proxy Pattern. The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, allowing you to control access to it. This pattern c
7 min read
Flyweight Pattern | C++ Design Patterns
A flyweight pattern is a structural design pattern used to optimize memory usage and performance when dealing with a large number of objects that share some common characteristics. It achieves this by separating an object's intrinsic state (shared among multiple objects) from its extrinsic state (unique to each object) and storing the intrinsic sta
9 min read
Introduction to Decorator Pattern in C++ | Design Patterns
The Decorator Pattern is a structural design pattern in software engineering that enables the dynamic addition of new behaviors or responsibilities to individual objects without altering their underlying class structure. It achieves this by creating a set of decorator classes that are used to wrap concrete components, which represent the core funct
12 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite helpful. Important Topics for the Memento MethodUnder
6 min read
Article Tags :
three90RightbarBannerImg