빌더 builder 패턴 - 자바스크립트 예제

SW설계
읽는데 3분 소요
처음 쓰여진 날: 2025-09-02
마지막 수정일: 2025-09-02

요약

빌더 builder 패턴을 자바스크립트 코드와 함께 알아봅니다.

빌더 (Builder) 패턴 요약

패턴 종류핵심 키워드
빌더 (Builder)복잡한 객체를 생성하는 과정을 단계별로 분리
빌더 패턴 감자
빌더 패턴 감자

빌더 (Builder) 패턴

빌더 패턴은 복잡한 객체를 생성하는 과정을 단계별로 분리하여, 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 디자인 패턴입니다. 특히 생성자의 매개변수가 많거나, 객체 생성 과정이 여러 단계로 나뉘어 복잡할 때 유용합니다.

이런 코드를 보신 적 있나요?

객체를 생성할 때 생성자의 매개변수가 너무 많아지는 경우를 '텔레스코핑 생성자 패턴(Telescoping Constructor Pattern)'이라고 부르기도 합니다.

javascript
// 💩 매개변수가 너무 많은 생성자
class HttpRequest {
  constructor(method, url, headers, body, timeout, retries, cache, useHttps) {
    this.method = method;
    this.url = url;
    this.headers = headers || {};
    this.body = body || null;
    this.timeout = timeout || 10000;
    this.retries = retries || 3;
    this.cache = cache || false;
    this.useHttps = useHttps || true;
  }
}

// 사용하기가 매우 불편합니다. 😫
const req = new HttpRequest(
  "GET",
  "https://api.example.com/data",
  { "Content-Type": "application/json" },
  null,
  15000,
  5,
  true,
  true
);

위 코드의 문제점은 다음과 같습니다.

  • 가독성 저하: 각 매개변수가 어떤 역할을 하는지 파악하기 어렵습니다.
  • 실수 유발: 매개변수의 순서를 잘못 입력하기 쉽습니다.
  • 유연성 부족: 일부 매개변수만 설정하고 싶어도 null이나 undefined를 계속 전달해야 합니다.

빌더 패턴으로 개선하기

빌더 패턴을 사용하면 이 문제를 깔끔하게 해결할 수 있습니다.

javascript
// Product (결과물)
class HttpRequest {
  constructor(builder) {
    this.method = builder.method;
    this.url = builder.url;
    this.headers = builder.headers;
    this.body = builder.body;
    this.timeout = builder.timeout;
    this.retries = builder.retries;
    this.cache = builder.cache;
    this.useHttps = builder.useHttps;
  }

  send() {
    console.log(`[${this.method}] ${this.url} 로 요청 전송 🚀`);
    // ... 실제 요청 로직 ...
  }
}

// Builder
class HttpRequestBuilder {
  constructor() {
    // 기본값 설정
    this.method = "GET";
    this.headers = {};
    this.timeout = 10000;
    this.retries = 3;
    this.cache = false;
    this.useHttps = true;
  }

  // 각 설정 메서드는 빌더 인스턴스 자신(this)을 반환합니다. (메서드 체이닝)
  setMethod(method) {
    this.method = method;
    return this; // 자신을 반환하여 메서드 체이닝 가능
  }

  setUrl(url) {
    this.url = url;
    return this;
  }

  setHeaders(headers) {
    this.headers = headers;
    return this;
  }

  setBody(body) {
    this.body = body;
    return this;
  }

  setTimeout(timeout) {
    this.timeout = timeout;
    return this;
  }

  // ... 다른 설정 메서드들 ...

  // 최종적으로 build() 메서드가 HttpRequest 객체를 생성합니다.
  build() {
    if (!this.url) {
      throw new Error("URL은 필수 항목입니다. ⚠️");
    }
    return new HttpRequest(this);
  }
}

// 사용법이 훨씬 명확하고 유연해졌습니다.
const request = new HttpRequestBuilder()
  .setMethod("POST")
  .setUrl("https://api.example.com/users")
  .setHeaders({ "Content-Type": "application/json" })
  .setBody({ name: "John Doe" })
  .setTimeout(5000)
  .build();

request.send(); // [POST] https://api.example.com/users 로 요청 전송 🚀

위 예시를 통해 복합 객체(많은 속성, 중첩 구조...)를 생성할 때 객체를 생성하는 방법(HttpRequestBuilder 클래스)과 객체를 구현하는 방법(HttpRequest 클래스)을 분리하는 빌더 패턴에 대해 알아봤습니다.

빌더 패턴 중요 키워드

  • 복합 객체(복잡한 객체)를 생성할때

  • 객체를 생성하는 방법(과정)

  • 객체를 구현(표현)하는 방법

  • 두 방법을 분리한다.

문제
복잡한 객체를 생성하는 과정을 단계별로 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 디자인 패턴으로, 텔레스코핑 생성자 패턴의 문제점을 해결하고 메서드 체이닝을 통해 가독성을 높이는 생성 패턴은?
보기
답변
정답정답 보기