본문 바로가기

Programinng/Design Pattern

자바(Java) - Builder Pattern 빌더 패턴

Builder Pattern은 생성자 패턴 중 하나이다.


흔히 우리가 사용하고 있는 생성자 패턴에는 Telescoping Pattern, JavaBeans Parttern이 있다.

텔리스코핑 패턴은 생성자 오버로딩(Overloading)을 말하며, 자바빈즈 패턴은 getter, setter 메소드를 이용한 필드값 초기화 방법이다.


텔리스코핑 패턴은 파라미터가 많을 경우 코드의 작성이 어려움이 있고, 가독성도 떨어진다. (파라미터는 없는게 최고로 좋고, 1개는 good, 2개는 not bad, 3개가 넘어가면 쓰레기 코드다.)


물론 예외도 있다. Point(x, y) 이런 경우는 적절하다.

인수가 2~3개가 필요하다면 다음가 괕이 일부를 독자적인 클래스를 만들어서 사용한다.

Circle.make(double x,double y,double radius);
Circle.make(Point point,double radius);


자바빈즈 패턴은 코드가 조금 길어지지만, 메소드가 명시적으로 있어서 가독성이 매우 좋다. 하지만 초기값을 셋팅하는 과정이 여러 setter 메소드로 나뉘어져 있어서 객체의 생성이 완료되기 전에 사용하려 하면 문제가 생길 수 있다. 또 setter메소드가 있기 때문에 불변(immutable) 클래스를 만들 수 없다.

 

이러한 문제점을 Builder Pattern으로 해결 할 수 있다.

public class BuilderPattern { 
    private int a; 
    private int b; 
    private int c; 
    private int d; 
     
    public static class Builder{ 
        private int a; 
        private int b; 
        private int c; 
        private int d; 
         
        public Builder a(int a){ 
            this.a = a; 
            return this
        } 
        public Builder b(int b){ 
            this.b = b; 
            return this
        } 
        public Builder c(int c){ 
            this.c = c; 
            return this
        } 
        public Builder d(int d){ 
            this.d = d; 
            return this
        } 
        public BuilderPattern build(){ 
            return new BuilderPattern(this); 
        } 
    } 
    private BuilderPattern(Builder builder){ 
        a = builder.a; 
        b = builder.b; 
        c = builder.c; 
        d = builder.d; 
    } 


이렇게 정의 한 후 다음과 같이 사용한다.


BuilderPattern builderPattern = new BuilderPattern.Builder().a(1).b(2).c(3).d(4).build();