아는 만큼 보인다/Design Pattern
Builder Pattern
eyevsky
2014. 12. 10. 13:34
- 사용 예
생성자 또는 정적 펙토리 메소드의 인자가 많고, 인자들 중 선택항목이 많은 경우, Builder 패턴의 적용을 생각해 볼 수 있음
- 코드
public class NutritionFacts {
private int necessaryA; // immutable object
private int optionalB;
private int optionalC;
// builder inner class
public static class Builder {
private int a = 0; // 기본값 초기화
private int b = 0;
private int c = 0;
public Builder(int a) {
this.a = a; // 필수값 생성시 설정
}
public Builder setB(int b) {
this.b = b;
return this;
}
public Builder setC(int c) {
this.c = c;
return this;
}
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
necessaryA = builder.a;
optionalB = builder.b;
optionalC = builder.c;
}
}
- 장점
선택 항목을 설정하는 메소드 이름으로 인해 클라이언트 코드의 가독성이 좋아 - 단점
inner class의 object를 먼저 생성해야 원하는 객체를 생성할 수 있음
- 출처 : Effective Java 2판, 규칙2. Builder 패턴 사용 고려
- inner class가 static 으로 선언되어 있어, outer class의 객체 생성전에 inner class에 접근 할 수 있다. 그래서 inner class의 객체를 먼저 생성하고 이 객체를 사용해 outer class의 객체를 생성해낸다. [본문으로]