빌더 패턴
- 복잡한 객체의 생성 과정 및 표현 방법을 분리하여 다양한 구성의 인스턴스를 만드는 생성 패턴
- 생성자의 매개 변수를 메서드를 통해 받아들이고 마지막에 통합 빌드해 객체를 생성하는 방식
구현
public class UserBuilder {
private Long id;
private String email;
private String nickName;
private String password;
private int age;
private int score;
public UserBuilder id(Long id) {
this.id = id;
return this;
}
public UserBuilder email(String email) {
this.email = email;
return this;
}
public UserBuilder nickName(String nickName) {
this.nickName = nickName;
return this;
}
public UserBuilder password(String password) {
this.password = password;
return this;
}
public UserBuilder age(int age) {
if (age < 0) {
throw new IllegalArgumentException("나이는 음수가 될 수 없습니다.");
}
this.age = age;
return this;
}
public UserBuilder score(int score) {
this.score = score;
return this;
}
public User build() {
return new User(id, email, nickName, password, age, score);
}
}
사용 이유
- 생성 과정이 복잡한 인스턴스를 일관된 프로세스로 생성
- 클래스 변수가 증가할 수록 생성자 방식은 어떤 멤버인지 파악이 어려움
- 빌더 사용 시 직관적으로 멤버변수를 파악할 수 있다.
- 빌더의 메서드 체이닝 형태로 호출하여 인스턴스 구성 및 객체 생성 유도
- 객체 생성 단계 지연
- 객체 생성을 단계별로 구성 또는 재귀적으로 처리 가능
- 멤버 변수 검증 및 초기화를 멤버별로 분리
- 생성자 방식은 각 생성자 메서드마다 복잡하게 구현
- 빌더 방식은 멤버 변수의 초기화를 각 멤버별로 분리해 작성 가능
단점
- 코드 복잡성 증가
- 여러 개의 클래스의 빌더 클래스를 생성해야 하므로 복잡성 증가
- 성능
- 메스드를 호출 후 빌더를 거치기 때문에 생성자보다 성능 하락
참고
빌더(Builder) 패턴 - 완벽 마스터하기
빌더 패턴