Skip to main content

Builder Pattern

Construct complex objects step by step with flexible configuration

Pattern Overview

🏗️ The Builder Pattern - Complex Object Construction

Constructs complex objects step by step, allowing different representations of the same construction process. Perfect for creating objects with many optional parameters!

  • Core Problem Solved:
  • Avoid telescoping constructor parameters
  • Create objects with complex initialization
  • Support different representations of same object
  • Enable step-by-step construction process
🔍 Three Implementation Approaches:
  • Method Chaining: Fluent interface with returning 'this'
  • Director Pattern: Separate builder from construction logic
  • Functional Builder: Immutable approach with function composition
  • Real-World Applications:
  • SQL query builders and ORM query construction
  • HTTP request builders in API clients
  • Configuration objects for complex systems
  • Test data builders in testing frameworks
  • UI component builders and form generators
  • Document and report generators
  • Modern Usage Examples:
  • React component prop builders
  • GraphQL query builders
  • Docker container configuration
  • Webpack configuration builders

Examples:
SQL query construction
Input:
QueryBuilder().select(['name', 'email']).from('users').where('active = 1')
Output:
SELECT name, email FROM users WHERE active = 1
House construction
Input:
HouseDirector.buildLuxuryHouse(new ModernHouseBuilder())
Output:
House with concrete foundation, glass walls, flat roof, garage, and pool
User profile creation
Input:
UserProfileBuilder.create('John', 'john@example.com').withAge(30).withTheme('dark')
Output:
UserProfile with name, email, age 30, and dark theme

Concepts

step-by-step constructionfluent interfaceobject composition

Complexity Analysis

Time:O(n)
Space:O(1)

Implementation

method-chaining

Time: O(n) | Space: O(1)
class QueryBuilder {
  private selectFields: string[] = [];
  private fromTable: string = '';
  private whereConditions: string[] = [];

  public select(fields: string[]): QueryBuilder {
    this.selectFields = [...fields];
    return this; // Enable chaining
  }

  public from(table: string): QueryBuilder {
    this.fromTable = table;
    return this;
  }

  public where(condition: string): QueryBuilder {
    this.whereConditions.push(condition);
    return this;
  }

  public build(): string {
    let query = `SELECT ${this.selectFields.join(', ')} FROM ${this.fromTable}`;
    
    if (this.whereConditions.length > 0) {
      query += ` WHERE ${this.whereConditions.join(' AND ')}`;
    }
    
    return query;
  }
}

// Usage
const query = new QueryBuilder()
  .select(['name', 'email'])
  .from('users')
  .where('active = 1')
  .where('age > 18')
  .build();