주요 개념
- Builder 클래스
- 빌더 패턴에서는 객체 생성을 담당하는 별도의 빌더 클래스를 사용합니다.
- 빌더 클래스는 객체 생성에 필요한 모든 매개변수를 메서드 체이닝(Method Chaining) 방식으로 설정할 수 있도록 합니다.
- 유동적인 인터페이스(Fluent Interface)
- 빌더 패턴은 유동적인 인터페이스를 제공하여, 메서드 체이닝(Method Chaining)을 통해 가독성이 높은 코드 작성을 가능하게 합니다.
- 불변 객체
- 빌더 패턴을 사용하면 객체 생성 후 변경할 수 없는 불변 객체를 쉽게 만들 수 있습니다.
예시
일반적인 객체 생성 방식
public class User {
private String username;
private String password;
private String email;
private int age;
public User(String username, String password, String email, int age) {
this.username = username;
this.password = password;
this.email = email;
this.age = age;
}
}
- 단점
- 객체 생성 시 매개변수의 순서를 틀릴 수 있습니다.
- 필요한 매개변수만 설정하기 어렵습니다.
빌더 패턴을 사용한 객체 생성
public class User {
private String username;
private String password;
private String email;
private int age;
private User(Builder builder) {
this.username = builder.username;
this.password = builder.password;
this.email = builder.email;
this.age = builder.age;
}
public static class Builder {
private String username;
private String password;
private String email;
private int age;
public Builder username(String username) {
this.username = username;
return this;
}
public Builder password(String password) {
this.password = password;
return this;
}
public Builder email(String email) {
this.email = email;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public User build() {
return new User(this);
}
}
// 기본 생성자를 private로 막기
private User() {}
}
- 기본 생성자를 막는 이유
- 외부에서 직접 객체를 생성할 수 없도록 합니다.
- 객체 생성은 Builder 클래스를 통해서만 가능하도록 합니다.
- 이를 통해 필수 필드들이 모두 설정되었는지 확인할 수 있습니다.
User user = new User.Builder()
.username("john_doe")
.password("secure_password")
.email("john.doe@example.com")
.age(30)
.build();
장점
- 가독성: 메서드 체이닝을 통해 객체 생성 과정을 명확하게 할 수 있어 코드 가독성이 높아집니다.
- 유연성: 필요한 매개변수만 설정할 수 있어, 선택적 매개변수 설정이 유연합니다.
- 불변성: 객체를 생성한 후 변경할 수 없게 만들어, 불변 객체를 쉽게 구현할 수 있습니다.
Share article