Builder Pattern - offering pre-defined Interfaces to set Individual Parts

CK CK 3788 
Created at
Updated at  
1,438 0 0

The Builder pattern is a creational design pattern that separates the construction of a complex object from its representation, allowing the same construction process to create various representations of the object. It does this by using a separate builder object to construct the object step-by-step, offering a fluent interface to set individual parts, and finally returning a complete, immutable object. This promotes cleaner code, improves code readability, and allows for easier object creation with various configurations.

 

The Builder pattern is a creational design pattern that separates the construction of a complex object from its representation. This allows the same construction process to create various representations of the object. Instead of creating the object directly with a constructor that takes many parameters (leading to potential problems with object mutability and constructor bloat), the Builder pattern uses a separate "builder" object to construct the object step-by-step.

 

Builder Pattern - offering pre-defined Interfaces to set Individual Parts

 

Here's a breakdown:

  • Problem: Creating complex objects with many attributes can lead to constructors with numerous parameters, making them difficult to read, use, and maintain. Also, it's hard to ensure that only valid combinations of attributes are used. Furthermore, it's difficult to create variations of the object with slight differences in attribute values.
  • Solution: The Builder pattern solves this by:
    • Decoupling object creation from its representation: The construction process is separate from the final object's structure.
    • Providing a fluent interface: Builders often use method chaining to build the object step-by-step in a readable way.
    • Supporting multiple representations: Different builder instances can create objects with different attribute combinations.
  • Structure: A Builder pattern typically involves:
    • Product: The complex object being built.
    • Builder: An abstract interface defining methods to set the attributes of the product.
    • Concrete Builders: Concrete implementations of the Builder interface, each responsible for building a specific variation of the product.
    • Director (optional): A class that coordinates the building process, often using a Concrete Builder to construct the object according to a specific algorithm or configuration.
  • Benefits:
    • Improved readability and maintainability: The construction process is clearer and easier to understand.
    • Reduced constructor bloat: Constructors are simplified, taking fewer arguments.
    • Flexibility in object creation: Different variations of the object can be created easily.
    • Immutability support: The built objects can be immutable, enhancing thread safety and predictability.
  • Example (Conceptual): Imagine building a car. A Builder pattern could have a CarBuilder interface with methods like setEngine(), setWheels(), setColor(), etc. You could then have concrete builders like SportsCarBuilder and TruckBuilder that implement CarBuilder and set attributes specific to their respective vehicle types. A Director might be used to manage the steps involved in assembling a complete car based on a specific configuration (e.g., a "luxury sports car" configuration might call specific methods on the SportsCarBuilder).

In essence, the Builder pattern is a powerful tool for creating complex objects in a controlled and flexible way, resulting in cleaner, more maintainable code.

 

The Builder Pattern is a creational design pattern used to construct complex objects step by step. It separates the construction process from the representation, allowing the same construction process to create different representations.

Here’s an example of the Builder Pattern in C++:


Example: Building a Car

We will create a Car object step by step, where each step specifies details such as engine, seats, and other features.

1. Product Class

The object to be built.

#include <iostream>
#include <string>

class Car {
private:
    std::string engine;
    int seats;
    bool airConditioner;

public:
    void setEngine(const std::string& engineType) { engine = engineType; }
    void setSeats(int seatCount) { seats = seatCount; }
    void setAirConditioner(bool hasAC) { airConditioner = hasAC; }

    void showSpecifications() const {
        std::cout << "Car Specifications:\n";
        std::cout << "Engine: " << engine << "\n";
        std::cout << "Seats: " << seats << "\n";
        std::cout << "Air Conditioner: " << (airConditioner ? "Yes" : "No") << "\n";
    }
};

2. Builder Interface

Defines the steps for building the object.

class CarBuilder {
public:
    virtual ~CarBuilder() = default;
    virtual void buildEngine() = 0;
    virtual void buildSeats() = 0;
    virtual void buildAirConditioner() = 0;
    virtual Car* getCar() = 0;
};

3. Concrete Builder

Implements the steps to build a specific type of product.

class SportsCarBuilder : public CarBuilder {
private:
    Car* car;

public:
    SportsCarBuilder() { car = new Car(); }
    ~SportsCarBuilder() { delete car; }

    void buildEngine() override { car->setEngine("V8 Turbo Engine"); }
    void buildSeats() override { car->setSeats(2); }
    void buildAirConditioner() override { car->setAirConditioner(true); }
    Car* getCar() override { return car; }
};

class SUVCarBuilder : public CarBuilder {
private:
    Car* car;

public:
    SUVCarBuilder() { car = new Car(); }
    ~SUVCarBuilder() { delete car; }

    void buildEngine() override { car->setEngine("V6 Engine"); }
    void buildSeats() override { car->setSeats(7); }
    void buildAirConditioner() override { car->setAirConditioner(true); }
    Car* getCar() override { return car; }
};

4. Director

Orchestrates the building process.

class CarDirector {
private:
    CarBuilder* builder;

public:
    void setBuilder(CarBuilder* b) { builder = b; }
    Car* constructCar() {
        builder->buildEngine();
        builder->buildSeats();
        builder->buildAirConditioner();
        return builder->getCar();
    }
};

5. Client Code

The client uses the Director and a Builder to create objects.

int main() {
    CarDirector director;

    // Building a sports car
    SportsCarBuilder sportsCarBuilder;
    director.setBuilder(&sportsCarBuilder);
    Car* sportsCar = director.constructCar();
    std::cout << "Sports Car:\n";
    sportsCar->showSpecifications();
    delete sportsCar;

    // Building an SUV car
    SUVCarBuilder suvCarBuilder;
    director.setBuilder(&suvCarBuilder);
    Car* suvCar = director.constructCar();
    std::cout << "\nSUV Car:\n";
    suvCar->showSpecifications();
    delete suvCar;

    return 0;
}

Output

Sports Car:
Car Specifications:
Engine: V8 Turbo Engine
Seats: 2
Air Conditioner: Yes

SUV Car:
Car Specifications:
Engine: V6 Engine
Seats: 7
Air Conditioner: Yes

Key Points

  1. Builder Pattern provides flexibility in constructing complex objects by focusing on individual parts.

  2. The Director manages the overall construction process but is independent of the actual building logic.

  3. The Concrete Builders define how specific parts of the object are constructed.

Tags Builder Pattern Creational Design Patterns Creational Patterns Facebook X
Comments 0
Similar posts
  1. Abstract Factory Pattern - Commonly Used for UI Themes or Objects
    1,470
  2. Software Design Patterns
    1,444
  3. Factory Method Pattern allows overriding to return different concrete object types
    1,532
  1. The Blueprint of Success: Why System Design and Architecture Matter?
    409
  2. Software Design Patterns Cheat Sheet
    3,350
  3. Various naming for the Software Architecture - I can't find Component-based Architecture, Functional Architecture
    3,341
  4. Observer Pattern
    2,401
  5. Optimize the performance of a search results page that experiences high traffic
    147
  6. System Design: High-Traffic Time-Deal Promotion System
    181
  7. Designing Resilient Infrastructure to Prevent Order Data Loss During Kafka Failures
    161
  8. Real-Time Inventory & WMS System Design
    250
  9. Enterprise-Scale 100k+ TPS Order Tracking System Architecture
    210
  10. Enterprise-Scale 100k+ TPS Order Processing System Architecture
    183
  11. Architecting Dynamic Scale-Out and Scale-In with Docker Containers
    136
  12. How to Design Redis Caching in Infrastructure Architecture
    161
  13. Architecture Design - Database Partitioning vs. Sharding
    159
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,255
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233