Introduction to Builder Pattern
Builder separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
The Problem
Complex objects with many optional parameters:
typescript1// Telescoping constructor anti-pattern2class Shipment {3 constructor(4 sender: Address,5 recipient: Address,6 packages: Package[],7 insurance?: number,8 signature?: boolean,9 fragile?: boolean,10 priority?: boolean,11 saturdayDelivery?: boolean,12 // ... more options13 ) {}14}1516// Hard to use - what do all these booleans mean?17new Shipment(sender, recipient, packages, 100, true, false, true, false);
The Solution: Builder
Step-by-step construction with fluent interface:
typescript1const shipment = new ShipmentBuilder()2 .from(senderAddress)3 .to(recipientAddress)4 .addPackage(package1)5 .addPackage(package2)6 .withInsurance(500)7 .requireSignature()8 .markFragile()9 .build();
Pattern Structure
typescript1interface Builder<T> {2 reset(): this;3 build(): T;4}56class ShipmentBuilder implements Builder<Shipment> {7 private shipment: Partial<Shipment> = {};89 reset(): this {10 this.shipment = {};11 return this;12 }1314 from(address: Address): this {15 this.shipment.sender = address;16 return this;17 }1819 to(address: Address): this {20 this.shipment.recipient = address;21 return this;22 }2324 build(): Shipment {25 this.validate();26 const result = this.shipment as Shipment;27 this.reset();28 return result;29 }3031 private validate(): void {32 if (!this.shipment.sender) throw new Error('Sender required');33 if (!this.shipment.recipient) throw new Error('Recipient required');34 }35}
When to Use Builder
- Complex construction - Many optional parameters
- Step-by-step - Object built incrementally
- Validation - Validate before creating
- Immutability - Create immutable objects
- Different representations - Same process, different results
Benefits
- Readable, self-documenting construction
- Prevents invalid object states
- Separates construction from representation
- Supports immutable objects
Summary
Builder is ideal for complex objects with many optional parameters. It provides a readable, fluent API and can validate objects before creation.