⭐빌더 패턴

팩토리 패턴에서 절차(단계)를 통해 복잡한 자식을 생성한다. 불필요한 절차는 생략해가면서 구조화 한다.

실제 적용 예시

  • 생성 예시
    1. 빌더 인터페이스 설계 (모든 절차를 설계한다.)
    2. 구상 빌더 설계 (n개 가능) + 빌더 절차 순서등 규칙 설계
    3. 단계별 메서드를 캡슐화 할수 있다.
  • 자동차를 만드는 컨테이너 벨트를 생각하면 좋다.
namespace BuilderPattern {
    export class UserBuilder {
        private name: string;
        private age: number;
        private phone: string;
        private address: string;

        constructor(name: string) {
            this.name = name;
        }

        get Name() {
            return this.name;
        }
        setAge(value: number): UserBuilder {
            this.age = value;
            return this;
        }
        get Age() {
            return this.age;
        }
        setPhone(value: string): UserBuilder {
            this.phone = value;
            return this;
        }
        get Phone() {
            return this.phone;
        }
        setAddress(value: string): UserBuilder {
            this.address = value;
            return this;
        }
        get Address() {
            return this.address;
        }

        build(): User {
            return new User(this);
        }
    }

    export class ~~User~~ {
        private name: string;
        private age: number;
        private phone: string;
        private address: string;

        constructor(builder: UserBuilder) {
            this.name = builder.Name;
            this.age = builder.Age;
            this.phone = builder.Phone;
            this.address = builder.Address
        }

        get Name() {
            return this.name;
        }
        get Age() {
            return this.age;
        }
        get Phone() {
            return this.phone;
        }
        get Address() {
            return this.address;
        }
    }

}
const user1: BuilderPattern.User = new BuilderPattern.UserBuilder("Jancsi")
                        .setAge(12)
                        .setPhone("0123456789")
                        .setAddress("asdf")
                        .build();

언제 사용할까 ?

의존 관계가 명확할때 효율적으로 컴포넌트 혹은 클래스(모델)을 관리하기 위해서 사용한다.

장점

  • 다양한 유형의 자식을 만들기 위한 구조화에 어려움이 있다면 단계별로 생성하는 것이 복잡도를 낮춰줄 수 있다.
  • 오퍼레이터를 적정히 사용할 수 있다.
  • 예시.

단점

  • 여러개의 빌더를 만들어야 한다.