반응형
Builder Pattern(빌더 패턴) 은 복잡한 객체를 단계적으로 생성할 수 있도록 도와주는 생성 패턴 중 하나입니다. 각 단계는 메서드 체이닝을 통해 구성되며, 최종적으로는 완성된 객체를 반환하는 구조입니다.
🧱 Builder Pattern이란?
Builder Pattern은 복잡한 객체의 생성 과정과 표현 방법을 분리하여, 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 해주는 패턴입니다. 특히, 필수 값과 선택 값을 구분해야 하거나 생성 단계가 여러 개일 때 유용합니다.
class CarBuilder {
constructor() {
this.car = {};
}
setBrand(brand) {
this.car.brand = brand;
return this;
}
setColor(color) {
this.car.color = color;
return this;
}
setEngine(engine) {
this.car.engine = engine;
return this;
}
build() {
return this.car;
}
}
const myCar = new CarBuilder()
.setBrand("Toyota")
.setColor("red")
.setEngine("Hybrid")
.build();
console.log(myCar);
✅ 장점
- 유연한 객체 구성: 단계적으로 속성을 설정할 수 있어 유연함
- 가독성과 유지보수 향상: 메서드 체이닝 방식으로 읽기 쉬운 코드 구성 가능
- 객체의 불변성 유지: build 단계 이전까지 외부에서 객체에 직접 접근 불가
❌ 단점
- 클래스 증가: 각 빌더마다 별도 클래스를 만들어야 하는 경우가 있음
- 간단한 객체에는 오버킬: 단순한 속성만 가진 객체에는 불필요하게 복잡함
- 추적 어려움: build 과정이 길어질수록 디버깅이 어려워질 수 있음
🛠️ 실전 예시: 사용자 프로필 빌더
class ProfileBuilder {
constructor() {
this.profile = {};
}
setName(name) {
this.profile.name = name;
return this;
}
setEmail(email) {
this.profile.email = email;
return this;
}
setAge(age) {
this.profile.age = age;
return this;
}
build() {
return this.profile;
}
}
const profile = new ProfileBuilder()
.setName("Jane")
.setEmail("jane@example.com")
.setAge(28)
.build();
console.log(profile);
🧩 결론
Builder Pattern은 복잡한 객체를 구조적이고 명확하게 구성하고자 할 때 매우 유용한 패턴입니다. 객체를 직접 생성하지 않고도 다양한 조합으로 설정할 수 있어 유지보수성과 유연성을 높일 수 있으며, 특히 옵션이 많은 생성자 구조를 대체하기에 적합합니다.
반응형
'Programing > javascript' 카테고리의 다른 글
| 자바스크립트 Proxy Pattern (0) | 2025.04.19 |
|---|---|
| 자바스크립트 Facade Pattern (0) | 2025.04.19 |
| 자바스크립트 Decorator Pattern (0) | 2025.04.19 |
| 자바스크립트 Module Pattern (0) | 2025.04.19 |
| 자바스크립트 Prototype Pattern (1) | 2025.04.19 |
| 자바스크립트 Singleton Pattern (0) | 2025.04.19 |
| 자바스크립트 Factory Pattern (0) | 2025.04.19 |
| 자바스크립트 Constructor Pattern (0) | 2025.04.19 |