규칙 1.생성자 인자가 많을 때는 Builder 패턴 적용을 고려하라
장점 1. 점층적 생성자 패턴에 비해 의미를 이해 하기 쉽다.
- 점층적 생성자 패턴의 경우 설정할 필요가 없는 인자를 전달해야하는 경우가 발생한다. 빌더 패턴의 경우 메소드를 통해 인자를 전달하기 때문에 메소드의 이름으로 의미를 파악하기 쉽다.
장점 2. 객체 일관성이 깨지지 않는다.
- 자바 빈 패턴의 경우 1회 함수 호출로 객체의 생성을 끝낼 수 없어 일시적으로 객체 일관성이 꺠질수 있다(생성자의 인자가 유효한지 검사를 하는 방법을 사용할 수 없다).
- 빌더 패턴의 경우 필수적 인자를 생성자에 전달하여 빌더 객체를 만들며(객체일관성 유지), 빌더 객체에 정의된 설정 메소드를 호출하여 선택적 인자를 전달받고 아무런 인자를
받지 않는 build 메소드를 통해 변경 불가능한(immutable) 객체를 만든다.
장점 3. 빌더 패턴은 인자가 많은 생성자 또는 정적 팩토리가 필요한 클래스를 설계할때, 특히 대부분의 인자가 선택적인 상황에 유용하다
- 클라이언트 가독성은 점층적 생성자 패턴을 따를 때 보다 훨씬 좋으며, 자바 빈 패턴보다 안전하다.
단점 1. 객체를 생성하려면 우선 빌더 객체를 생성해야한다.
단점 2. 성능이 중요한 프로그램의 경우 빌더 패턴이 가지고 있는 오버헤드를 고려해야한다.
Java Class Diagram generate by intelli J

Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | package chapter02.item02.builder;
/** * Created by Jang Jeong Hyeon on 2017-08-03. */
// Builder Pattern public class NutritionFacts { private final int servingSize; private final int servings; private final int calories; private final int fat; private final int sodium; private final int carbohydrate;
public static class Builder{ // Required parameters private final int servingSize; private final int servings;
// Optimal Parameters - initialized to default values private int calories = 0; private int fat = 0; private int carbohydrate = 0; private int sodium = 0;
public Builder(final int servingSize, final int servings){ this.servingSize = servingSize; this.servings = servings; }
public Builder calories(final int cal){ this.calories = cal; return this; }
public Builder fat(final int fat){ this.fat = fat; return this; }
public Builder carbohydrate(final int carbohydrate){ this.carbohydrate = carbohydrate; return this; }
public Builder sodium(final int sodium){ this.sodium = sodium; return this; }
public NutritionFacts build(){ return new NutritionFacts(this); } }
private NutritionFacts(Builder builder){ this.servingSize = builder.servingSize; this.servings = builder.servings; this.calories = builder.calories; this.fat = builder.fat; this.sodium = builder.sodium; this.carbohydrate = builder.carbohydrate; }
public static void main(String[] args) { NutritionFacts cocaCola = new Builder(240,8) .calories(100) .sodium(35) .carbohydrate(27) .build(); System.out.println(cocaCola.calories); }}
| cs |
Out Put
