출처
https://simpleweb.tistory.com/m/9
https://ttum.tistory.com/m/35
https://yceffort.kr/2021/01/nodejs-4-design-pattern#%EB%B9%8C%EB%8D%94
빌더 패턴이란?
객체를 만들어 사용하다 보면 간혹 객체 생성자가 너무 길어지거나 복잡해지는 경우가 생긴다. 이런 경우 빌더 패턴은 객체의 생성 과정을 분리해 순차적이고 직관적으로 만든다.
팩토리 패턴과 마찬가지로 객체 구조와 객체를 분리하는 특성이 있고, 단순한 객체를 만들 때는 과한 기능일 수 있지만, 복잡한 객체를 만들 때는 단순화 하는데 도움을 준다.
객체를 Immutable하게 유지할 수도 있다.
객체 생성 코드의 가독성과 유지보수성이 높아진다.
//생성자의 매개변수가 많은 클래스
class Person {
constructor(name, age, gender, height, weight, address, phone) {
this.name = name;
this.age = age;
this.gender = gender;
this.height = height;
this.weight = weight;
this.address = address;
this.phone = phone;
}
introduce() {
console.log(`My name is ${this.name}, and I'm ${this.age} years old. I'm a ${this.gender}.`);
}
}
// Person class의 빌더 클래스 만들기
class PersonBuilder {
constructor(name) {
this.person = new Person();
this.person.name = name;
}
setAge(age) {
this.person.age = age;
return this;
}
setGender(gender) {
this.person.gender = gender;
return this;
}
setHeight(height) {
this.person.height = height;
return this;
}
setWeight(weight) {
this.person.weight = weight;
return this;
}
setAddress(address) {
this.person.address = address;
return this;
}
setPhone(phone) {
this.person.phone = phone;
return this;
}
build() {
return this.person;
}
}
//객체 생성
let person = new PersonBuilder('홍길동')
.setAge(32)
.setGender('male')
.setHeight(180)
.setWeight(80)
.setAddress('경기도 고양시')
.setPhone('123-456-7890')
.build();
// 클래스 안에 클래스
export default class User {
#name;
#age;
constructor(builder) {
this.#name = builder.getName();
this.#age = builder.getAge();
}
getName() {
return this.#name;
}
getAge() {
return this.#age;
}
static Builder = class {
#name = "";
#age = 0;
getName() {
return this.#name;
}
setName(name) {
this.#name = name;
return this;
}
getAge() {
return this.#age;
}
setAge(age) {
this.#age = age;
return this;
}
build() {
return new User(this);
}
};
}
// 객체 생성
const user = new User.Builder()
.setName('kate')
.setAge(15);
'개발 > Javascript(Typescript)' 카테고리의 다른 글
[자바스크립트] 이벤트루프 (0) | 2023.08.17 |
---|---|
[디자인 패턴] 프로토타입 (0) | 2023.08.16 |
[디자인 패턴] 팩토리 패턴 (0) | 2023.08.09 |
[디자인 패턴] 싱글톤 (0) | 2023.08.08 |
타입스크립트 4 - 클래스 (0) | 2023.07.21 |