Java

빌더 패턴(Builder pattern)을 써야하는 이유, @Builder

초보병일이 2023. 2. 7. 18:51
728x90

빌더 패턴(Builder pattern)이란?

객체를 정의하고 그 객체를 생성할 때 보통 생성자를 통해 생성하는 것을 생각한다.

 

객체를 생성할 수 있는 빌더를 builder() 함수를 통해 얻고 거기에 셋팅하고자 하는 값을 셋팅하고 마지막에 build()를 통해 빌더를 작동 시켜 객체를 생성한다.

 

빌더를 왜 써야할까?

1. 생성자 파라미터가 많을 경우 가독성이 좋지 않다.

2. 값을 넣는 순서가 상관이 없다.

 

1번

User oneUser = new User( "test@test", "test1", "bang", "010-1234-1234",
        "dsa", "hi", "n", "ahffk", "dsa", LocalDateTime.now());

이런 경우에 어떤 값을 넣어야 되고 어떤 순서인지 너무 헷갈리지 않는가?

처음 설계할 땐, 괜찮을지 몰라도

유지보수가 필요할 때, 어떤 값을 의미하는지 이해가 힘들어진다.

 

빌더 패턴을 이용하면?

User user = User.builder()
        .email("test@test")
        .password("test1")
        .nickname("bang")
        .phoneNumber("010-1234-1234")
        .userImage("dsa")
        .introduction("hi")
        .withdrawYn("n")
        .role("ahffk")
        .refresh_token("dsa")
        .withdrawAt(LocalDateTime.now())
        .build();

어떤 값을 의미하는지 쉽게 알 수 있다.

 

2번

값의 순서가 중요하지 않다.

public User(String email, String password, String nickname,
            String phoneNumber, String userImage, String introduction,
            String withdrawYn, String role, String refresh_token,
            LocalDateTime withdrawAt) {
    this.email = email;
    this.password = password;
    this.nickname = nickname;
    this.phoneNumber = phoneNumber;
    this.userImage = userImage;
    this.introduction = introduction;
    this.withdrawYn = withdrawYn;
    this.role = role;
    this.refresh_token = refresh_token;
    this.withdrawAt = withdrawAt;
}

이렇게 생성자를 생성해도 빌드 패턴을 이용하면

User user = User.builder()
        .password("test1")
        .email("test@test")
        .nickname("bang")
        .userImage("dsa")
        .introduction("hi")
        .phoneNumber("010-1234-1234")
        .refresh_token("dsa")
        .role("ahffk")
        .withdrawYn("n")
        .withdrawAt(LocalDateTime.now())
        .build();

순서가 뒤죽박죽이여도 정상 작동한다.

 

사용법

@Builder
public User(String email, String password, String nickname,
            String phoneNumber, String userImage, String introduction,
            String withdrawYn, String role, String refresh_token,
            LocalDateTime withdrawAt) {
    this.email = email;
    this.password = password;
    this.nickname = nickname;
    this.phoneNumber = phoneNumber;
    this.userImage = userImage;
    this.introduction = introduction;
    this.withdrawYn = withdrawYn;
    this.role = role;
    this.refresh_token = refresh_token;
    this.withdrawAt = withdrawAt;
}

이렇게 생성자 위에 @Builder만 넣어주면 됨!

 

Lombok은 정말 신세계...!

@Builder에 자세한 내용은 내가 더 공부하면서 추가할 예정!

728x90