Builder Pattern
CreationalWhat is it?
Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
Why use it?
The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations. This is particularly useful when an object needs to be created step-by-step or when the creation process must allow different representations of the object (e.g., creating different flavors of a product).
Code Example
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Builder Pattern Example
class Computer {
constructor() {
this.parts = {};
}
addPart(name, value) {
this.parts[name] = value;
}
getSpecs() {
return Object.entries(this.parts)
.map(([key, value]) => `${key}: ${value}`)
.join('\n');
}
}
class ComputerBuilder {
constructor() {
this.computer = new Computer();
}
addCPU(cpu) {
this.computer.addPart('CPU', cpu);
return this;
}
addRAM(ram) {
this.computer.addPart('RAM', ram);
return this;
}
addStorage(storage) {
this.computer.addPart('Storage', storage);
return this;
}
addGPU(gpu) {
this.computer.addPart('GPU', gpu);
return this;
}
addPowerSupply(powerSupply) {
this.computer.addPart('Power Supply', powerSupply);
return this;
}
build() {
return this.computer;
}
}
// Director class that knows how to build specific configurations
class ComputerDirector {
static buildGamingPC(builder) {
return builder
.addCPU('Intel Core i9-12900K')
.addRAM('32GB DDR5')
.addStorage('2TB NVMe SSD')
.addGPU('NVIDIA RTX 4090')
.addPowerSupply('850W 80+ Gold')
.build();
}
static buildOfficePC(builder) {
return builder
.addCPU('Intel Core i5-12400')
.addRAM('16GB DDR4')
.addStorage('512GB SSD')
.addGPU('Integrated Graphics')
.addPowerSupply('450W 80+ Bronze')
.build();
}
static buildWorkstation(builder) {
return builder
.addCPU('AMD Threadripper PRO 5995WX')
.addRAM('128GB ECC DDR4')
.addStorage('4TB NVMe SSD + 10TB HDD')
.addGPU('NVIDIA RTX A6000')
.addPowerSupply('1200W 80+ Platinum')
.build();
}
}
// Usage
const gamingPC = ComputerDirector.buildGamingPC(new ComputerBuilder());
console.log('Gaming PC Specs:\n' + gamingPC.getSpecs());
const officePC = ComputerDirector.buildOfficePC(new ComputerBuilder());
console.log('\nOffice PC Specs:\n' + officePC.getSpecs());
// Custom build
const customPC = new ComputerBuilder()
.addCPU('AMD Ryzen 7 5800X')
.addRAM('16GB DDR4')
.addStorage('1TB SSD')
.addGPU('AMD RX 6700 XT')
.build();
console.log('\nCustom PC Specs:\n' + customPC.getSpecs());
Quick Facts
- Category
- Creational
- Common Use Cases
- Object creation, instance management