Builder 패턴이란
- 객체를 단계별로 생성할 수 있게 도와주는 생성 패턴
- 복잡한 생성자 호출 대신, 메서드 체인으로 원하는 속성을 설정하고 마지막에 .build()로 객체를 완성
- new로 직접 객체를 만들면 파라미터 순서를 기억해야 하고 가독성이 떨어지는데, 빌더는 그 문제를 해결해줌
쓰는 상황
- 생성할 객체에 옵션이 많을때 (필수/선택 속성 섞여있을 때)
- 생성 과정이 여러 단계로 나눠질때
- 같은 객체라도 조합에 따라 다르게 생성해야 할 때
빌더가 없는 상황에서 new User 객체를 생성한다면?
class User {
constructor(
public id: number,
public name: string,
public email?: string,
public phone?: string,
public address?: string
) {}
}
const user = new User(1, "홍길동", "test@test.com", undefined, "서울");
빌더 패턴을 적용하여 new User 객체를 생성한다면?
class User {
id: number;
name: string;
email?: string;
phone?: string;
address?: string;
constructor(builder: UserBuilder) {
this.id = builder.id;
this.name = builder.name;
this.email = builder.email;
this.phone = builder.phone;
this.address = builder.address;
}
}
class UserBuilder {
id: number;
name: string;
email?: string;
phone?: string;
address?: string;
setId(id: number): this {
this.id = id;
return this;
}
setName(name: string): this {
this.name = name;
return this;
}
setEmail(email: string): this {
this.email = email;
return this;
}
setPhone(phone: string): this {
this.phone = phone;
return this;
}
setAddress(address: string): this {
this.address = address;
return this;
}
build(): User {
return new User(this);
}
}
const user = new UserBuilder()
.setId(1)
.setName("홍길동")
.setEmail("test@test.com")
.setAddress("서울")
.build();
console.log(user);
위와 같은 개발로,메서드체인 할 시, 순서가 상관없고, 필요없는 설정은 건드리지 않아도 되며, 가독성이 올라감
쓰이는 사례
- 프론트: Form 값 기반으로 DTO(Data Transfer Object) 만들 때
- 백엔드: DB Insert/Update용 객체 생성, Query 객체 조립
'디자인패턴' 카테고리의 다른 글
| Prototype 패턴 (0) | 2025.09.12 |
|---|---|
| Abstract Factory (추상 팩토리 패턴) (0) | 2025.09.09 |
| Factory Method 패턴 (0) | 2025.09.09 |
| singleton(싱글턴) 패턴 (0) | 2025.09.05 |
댓글