public class NutritionFacts {
private final int servingSize;
private final int calories;
private final int transFat;
private final int saturatedFat;
private final int protein;
private final int sodium;
}
점층적 생성자 패턴
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 NutritionFacts(int servingSize, int servings) {
this(servingSize, servings, 0);
}
public NutritionFacts(int servingSize, int servings, int calories) {
this(servingSize, servings, calories, 0);
}
public NutritionFacts(int servingSize, int servings, int calories, int fat) {
this(servingSize, servings, calories, fat, 0);
}
public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium) {
this(servingSize, servings, calories, fat, sodium, 0);
}
public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate) {
this.servingSize = servingSize;
this.servings = servings;
this.calories = calories;
this.fat = fat;
this.sodium = sodium;
this.carbohydrate = carbohydrate;
}
}
자바빈즈 패턴
NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setSomething1();
cocaCola.setSomething2();
점층적 생성자 패턴의 안전성과 자바 빈즈 패턴의 가독성을 겸비
NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).build();
흐름
빌더는 보통 생성할 클래스 안에 정적 멤버 클래스로 만들어둠
가변인수 매개변수를 여러 개 사용할 수 있음
public static class Builder {
private int field1;
private String[] field2 = new String[0]; // 기본값 빈 배열
private double[] field3 = new double[0]; // 기본값 빈 배열
public Builder setField1(int field1) {
this.field1 = field1;
return this;
}
public Builder setField2(String... field2) {
this.field2 = field2;
return this;
}
public Builder setField3(double... field3) {
this.field3 = field3;
return this;
}
public ComplexObject build() {
return new ComplexObject(this);
}
}
//클라이언트 코드
public class Client {
public static void main(String[] args) {
ComplexObject obj = new ComplexObject.Builder()
.setField1(10)
.setField2("value1", "value2", "value3") // 가변인수
.setField3(1.1, 2.2, 3.3) // 가변인수
.build();
// 객체 사용
System.out.println("Object created with field1: " + obj.field1);
}
}