Java/디자인 패턴

생성 패턴 _ 빌더 패턴

minquu 2025. 7. 21. 13:31
반응형

🧱 빌더 패턴 (Builder Pattern)

1. 패턴 개요

Builder 패턴은 복잡한 객체의 생성 과정을 분리하여, 같은 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 해주는 생성 패턴입니다.

📌 목적: 생성자가 너무 많거나 복잡할 때, 생성 절차를 메서드 체이닝 방식으로 분리하여 가독성과 안정성을 확보


2. 언제 사용하나요?

  • 파라미터가 많은 생성자 대신 가독성 있는 객체 생성을 원할 때
  • 필수/옵션 필드를 구분하고 싶을 때
  • 생성 순서를 조절하거나, 다양한 설정 조합이 필요한 객체일 때
  • 불변 객체를 만들고 싶을 때

3. 장단점 비교

장점 👍 단점 👎
필드가 많을 때 가독성이 높아짐 클래스 수가 증가할 수 있음
객체 생성 절차를 캡슐화 복잡도 증가 가능
불변 객체 생성 가능 단순한 객체에는 과할 수 있음
메서드 체이닝으로 가독성 향상 구현이 길어질 수 있음

4. 예제 코드 (Java)

📦 Computer 클래스

public class Computer {
    private String cpu;
    private String ram;
    private int ssd;
    private boolean hasGraphicCard;

    private Computer(Builder builder) {
        this.cpu = builder.cpu;
        this.ram = builder.ram;
        this.ssd = builder.ssd;
        this.hasGraphicCard = builder.hasGraphicCard;
    }

    public static class Builder {
        private String cpu;
        private String ram;
        private int ssd = 0;
        private boolean hasGraphicCard = false;

        public Builder(String cpu, String ram) {
            this.cpu = cpu;
            this.ram = ram;
        }

        public Builder ssd(int ssd) {
            this.ssd = ssd;
            return this;
        }

        public Builder hasGraphicCard(boolean hasGraphicCard) {
            this.hasGraphicCard = hasGraphicCard;
            return this;
        }

        public Computer build() {
            return new Computer(this);
        }
    }

    public String toString() {
        return cpu + ", " + ram + ", " + ssd + "GB SSD, Graphic Card: " + hasGraphicCard;
    }
}

클라이언트 클래스 (director 클래스 라고도 함)

Computer pc = new Computer.Builder("Intel i7", "16GB")
                    .ssd(512)
                    .hasGraphicCard(true)
                    .build();

System.out.println(pc);

✅ 핵심 요약

•    메서드 체이닝으로 가독성 향상
•    선택적 매개변수 설정 가능
•    생성자 오염 방지
•    복잡한 객체 생성 분리
반응형