codingBird

[이펙티브 자바] - Item 2 생성자에 매개변수가 많다면 빌더를 고려하라. 본문

JAVA

[이펙티브 자바] - Item 2 생성자에 매개변수가 많다면 빌더를 고려하라.

김뚜루 2023. 4. 15. 09:51

Item2 - 생성자에 매개변수가 많다면 빌더를 고려하라.

점층적 생성자 패턴은 매개변수 개수가 많아지면 클라이언트 코드를 작성하거나 읽기 어려워진다.

자바빈즈 패턴은 객체의 일관성이 깨져 오류가 발생하기 쉽다.

필수 인자와 필수 인자가 아닌 값들을 필드로 가지는 객체를 생성할 때 명명된 선택적 매개변수를 흉내낸 빌더를 사용해 유연하게 생성해보자.

 

public class Product {
    private String name;
    private int price;
    private String color;
    private String size;

    private Product(Builder builder) {
        this.name = builder.name;
        this.price = builder.price;
        this.color = builder.color;
        this.size = builder.size;
    }

    // getters
    // ...
    
    public static class Builder {
        private String name;
        private int price;
        private String color;
        private String size;

        public Builder(String name, int price) {
            this.name = name;
            this.price = price;
        }

        public Builder color(String color) {
            this.color = color;
            return this;
        }

        public Builder size(String size) {
            this.size = size;
            return this;
        }

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

Product product = new Product.Builder("phone", 1000)
                        .color("black")
                        .size("large")
                        .build();