[디자인 패턴(Design Pattern)] 빌더(Builder)

업데이트:

카테고리:

태그:


빌더 패턴이란?

빌더 패턴은 생성 패턴 중의 하나로 객체의 생성 과정과 표현 방법을 분리하여 객체의 생성을 유연하게 하는 디자인 패턴이다.

장점

  • 객체의 필드 값을 생성과정에서 선택적으로 입력할 수 있다.
  • 즉, 객체를 생성하는 절차를 세밀하게 나눌 수 있다.

코틀린에서의 빌더 패턴

코틀린에서는 생성자를 호출할 때 입력하는 인자들의 이름을 명시할 수 있고 기본 값을 정의하는 것으로 필요한 프로퍼티에만 값을 입력하고 나머지는 기본 값으로 초기화 할 수 있기 때문에 빌더 패턴이 필요하지 않다.

예시 (java)

이름과 나이 그리고 형제, 자매 여부를 속성으로 가지는 Man객체를 생성할 ManBuilder를 만들어보자.

우선 생성할 객체의 정보를 담을 Man 클래스를 생성한다. 빌더를 통해서만 생성을 할 것이므로 생성자는 Private으로 선언한다.

public class Man {
    private String name;
    private int age;

    private boolean hasBrother;
    private boolean hasSister;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public boolean hasBrother() {
        return hasBrother;
    }

    public boolean hasSister() {
        return hasSister;
    }

    private Man(){}
}

이제 해당 클래스의 내부에 ManBuilder 클래스를 생성한다. 이때 빌더를 static class로 만들어 독립적인 생성이 가능하도록 한다.

public static class ManBuilder{
    private String name;
    private int age;

    private boolean hasBrother;
    private boolean hasSister;

    public ManBuilder(String name,int age){
        this.name = name;
        this.age = age;
    }

    public ManBuilder setHasBrother(boolean tf){
        this.hasBrother = tf;
        return this;
    }

    public ManBuilder setHasSister(boolean tf){
        this.hasSister = tf;
        return this;
    }

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

그리고 다시 Man클래스로 돌아가 빌더를 인자로 받는 생성자를 만든다.

private Man(ManBuilder mb){
    this.name = mb.name;
    this.age = mb.age;
    this.hasBrother = mb.hasBrother;
    this.hasSister = mb.hasSister;
}

이제 다음 코드를 이용해 Man 객체를 생성해보자

Man man = new Man.ManBuilder("김철수",22)
                .setHasBrother(false)
                .setHasSister(true)
                .build();