Skip to content

빌더 패턴은 복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴이다. 빌더 패턴을 사용하면 객체를 생성할 떄 필요한 값만 넣을 수 있다. 그리고 파라미터룰 사용한 생성자가 아니라 변수명을 명시하여 생성하는 것이기 때문에 변수 순서가 바뀌거나 새로 추가될때 유연하게 대처할 수 있고 매개변수가 많아져도 가독성을 높일 수 있다.

구현하는 것이 복잡하기 때문에 직접 구현하면 코드 구조가 읽기 어려워진다는 단점이 있다. Lombok에서 제공해주는 @Builder 어노테이션을 사용하면 Lombok이 자동으로 빌더를 만들어준다.


예시 코드

@Getter
@Setter
public class Pizza {
String name;
String topping;
String sauce;
public Pizza(String name, String topping, String sauce) {
this.name = name;
this.topping = topping;
this.sauce = sauce;
}
public static PizzaBuilder builder() {
return new PizzaBuilder();
}
public static class PizzaBuilder {
String name;
String topping;
String sauce;
PizzaBuilder(){}
public Pizza build() {
return new Pizza(this.name, this.topping, this. sauce);
}
public PizzaBuilder name(String name){
this.name = name;
return this;
}
public PizzaBuilder topping(String topping){
this.topping = topping;
return this;
}
public PizzaBuilder sauce(String sauce){
this.sauce = sauce;
return this;
}
}
}

링크로 가면 코드를 볼 수 있다.