Spring

Builder 패턴

mean-ji 2022. 9. 2. 17:30
728x90

Lombok을 이용해 @Getter, @Setter를 사용하여 사용하고 있었는데, 빌더 패턴이라는 것을 알게 되었고

꽤 많은 장점이 있는 것 같아서 공부해 보게 되었다.

 

Builder 패턴은 Effective Java의 규칙인 것 같다.

(최근 Effective Java에 대해 알게 되었는데 궁금해서 이 부분도 추가로 공부해 볼 예정이다.)

🥑 생성자에 인자가 많을 때는 빌더 패턴을 고려

빌더 패턴이란 복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게하는 패턴이라고 한다.

레퍼런스 블로그 개발자 분은 생성자가 많아지면 빌더 패턴을 만드는 편이라고 한다.

이유로는 빌더 패턴을 활용하면 어떤 필드에 어떤 인자를 넣어 주었는지 명확히 알 수 있고, 넣어줄 필요가 없는 필드는 굳이 선언할 필요가 없어서 선호하는 편이라고 함. 하지만 필드에 null이 들어간다는 걸 명확히 볼 수 있는 점 때문에 생성자를 통해 객체를 생성하는 방법을 택하는 개발자 분들도 있다고 한다.

 

Builder 패턴의 장점

1. 객체들마다 들어가야 할 인자가 각각 다를 때 유연하게 사용할 수 있다.

2. Setter 생성을 방지하고 불변 객체로 만들 수 있다.

3. 필수 argument를 지정할 수 있다. (PK 역할을 할 ID값이 보통이라고 한다.)

 

Builder 패턴을 작성하는 방법

public static class Builder {
    private final Profession profession;
    private final String name;
    private HairType hairType;
    private HairColor hairColor;
    private Armor armor;
    private Weapon weapon;
    
    public Builder(Profession profession, String name) {
        if (profession == null || name == null) {
            throw new IllegalArgumentException("profession and name can not be null");
        }
        this.profession = profession;
        this.name = name;
    }
    
    public Builder withHairType(HairType hairType) {
        this.hairType = hairType;
        return this;
    }
    
    public Builder withHairColor(HairColor hairColor) {
        this.hairColor = hairColor;
        return this;
    }
    
    public Builder withArmor(Armor armor) {
        this.armor = armor;
        return this;
    }
    
    public Builder withWeapon(Weapon weapon) {
        this.weapon = weapon;
        return this;
    }
    
    public Hero build() {
        return new Hero(this);
    }
}
Hero mage = new Hero.Builder(Profession.Mage, "Riobard")
                .withHairColor(HairColor.BLACK)
                .withWeapon(Weapon.DAGGER)
                .build();

 

@Builder

빌더 패턴으로 클래스를 만들 때 위와 같은 방법으로 클래스를 만들면 너무 길고 불편하다.

그래서 Lombok에 @Builder를 사용하면 보일러플레이트 코드를 줄일 수 있다.

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder(builderMethodName = "TodoListBuilder")
@ToString
public class todoList {
    
    private Long id;
    private String title;
    private String content;
    
    public static TodoListBuilder builder(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("필수 파라미터 누락");
        }
        return travelCheckListBuilder().id(id);
    }
}
public class Main {
    public static void main(String[] args) {
        TodoList todoList = TodoList.builder()
                        .title("글 쓰기")
                        .content("블로그에 글을 써야해요")
                        .build();
    }
}

 

 


Reference

https://zorba91.tistory.com/298

https://github.com/greekZorba/java-design-patterns/tree/master/builder

 

728x90