💡 점층적 생성자 패턴(telescoptin constructor pattern)
정적 팩터리와 생성자에는 똑같은 제약이 하나 있는데, 선택적 매개변수가 많을 때 적절히 대응하기 어렵다는 점이다. 보통 점층적 생성자 패턴(telescoping constructor pattern)을 즐겨 사용하여, 생성자의 형태를 여럿 만들어 사용했다.
public class Car {
private String model;
private String color;
private int year;
private boolean isElectric;
public Car(String model) {
this.model = model;
}
public Car(String model, String color) {
this.model = model;
this.color = color;
}
public Car(String model, String color, int year) {
this.model = model;
this.color = color;
this.year = year;
}
public Car(String model, String color, int year, boolean isElectric) {
this.model = model;
this.color = color;
this.year = year;
this.isElectric = isElectric;
}
}
위의 코드처럼, 선택적 매개변수가 늘어날 수록 생성자를 늘려가는 방식이다. 보통 이런 생성자는 사용자가 설정하기 원치 않는 매개변수까지 포함하기 쉬운데, 어쩔 수 없이 그런 매개변수에도 값을 지정해야 한다. 이는 매개변수 개수가 많아지면 코드를 이해하기 어려워진다.
💡 자바빈즈 패턴(JavaBeans pattern)
이 때 활용할 수 있는 다른 대안인 자바빈즈 패턴(JavaBeans pattern)은 다음과 같다.
public class Car {
private String model;
private String color;
private int year;
private boolean isElectric;
public void setModel(String model) {
this.model = model;
}
public void setColor(String color) {
this.color = color;
}
public void setYear(int year) {
this.year = year;
}
public void setElectric(boolean isElectric) {
this.isElectric = isElectric;
}
}
점층적 생성자 패턴의 단점인 매개변수의 수가 많아졌을 때, 타입이 같은 매개변수가 연달아 늘어서 있을 때 발생할 수 있는 클라이언트 실수들을 만들지 않을 수 있다. 코드가 길어지지만 그만큼 인스턴스를 만들기 쉽고, 읽기 쉬운 코드가 된다.
하지만 자바빈즈는 심각한 단점이 존재하는데, 객체를 하나 만들려면 메서드를 여러 개 호출해야 하고, 객체가 완전히 생성되기 전까지는 일관성(consistency)이 무너진 상태에 놓이게 된다는 점이다.
점층적 생성자 패턴에서는 매개변수들이 유효한지만 확인하면 일관성을 유지할 수 있지만, 자바빈즈 패턴은 그렇지 않다. 일관성이 깨진 객체가 만들어지면, 버그가 있는 코드와 런타임 문제를 겪는 코드가 물리적으로도 떨어져 있으므로 디버깅도 쉽지 않다. 이 문제 때문에 자바빈즈 패턴에서는 클래스를 불변으로 만들 수 없으며, 스레드 안정성을 위해 프로그래머가 추가 작업을 해주어야 한다. 이 단점을 완화하기 위해 생성이 끝난 객체를 수동으로 '얼리고(freezing)', 얼리기 전에는 사용할 수 없도록 하기도 한다. 하지만 사용이 어렵고, 객체 사용 전에 freeze 메서드를 확실히 호출해줬는지를 컴파일러가 보증할 방법이 없어 런타임 오류에 취약하다.
💡 빌더 패턴(Builder pattern)
클라이언트는 필요한 객체를 직접 만드는 대신, 필수 매개변수만으로 생성자(혹은 정적 팩터리)를 호출해 빌더 객체를 얻는다. 그런 다음 빌더 객체가 제공하는 일종의 세터 메서드들로 원하는 선택 매개변수를 설정한다. 마지막으로 매개변수가 없는 build 메서드를 호출해 빌더 객체를 얻는다.
클래스는 불변이며, 모든 매개변수의 기본 값을 모아 두고, 빌더의 세터 메서드들은 빌더 자신을 반환하기 때문에 연쇄적으로 호출할 수 있다.
public class Car {
private final String model;
private final String color;
private final int year;
private final boolean isElectric;
public static class Builder {
// 필수 매개변수
private final String model;
private String color = "";
private int year = 0;
private boolean isElectric = false;
public Builder(String model) {
this.model = model;
}
public Builder color(String color) {
this.color = color;
return this;
}
public Builder year(int year) {
this.year = year;
return this;
}
public Builder isElectric(boolean isElectric) {
this.isElectric = isElectric;
return this;
}
public Car build() {
return new Car(this);
}
}
private Car(Builder builder) {
model = builder.model;
color = builder.color;
year = builder.year;
isElectric = builder.isElectric;
}
public String toString() {
return "Model: ["+this.model+"] Color: ["+this.color+"] Year: ["+this.year+"] Electric: ["+this.isElectric+"]";
}
}
위 코드처럼 빌더 패턴을 사용하여 Car 클래스를 구현할 수 있다.
public class Main {
public static void main(String[] args) {
Car car = new Car.Builder("GV70").color("gray").year(1).isElectric(false).build();
System.out.println(car.toString());
}
}
이처럼 Car 클래스는 불변이며, 모든 매개변수의 기본값을 한곳에 모아 둔다. (ex. "", 0, false) 빌더의 세터 메서드들은 빌더 자신을 반환하여 연쇄적으로 호출이 가능하다. 이러한 방식을 메서드 호출이 흐르듯 연결된다는 뜻으로 플루언트 API(fluent API) 혹은 메서드 연쇄(method chaining)라 한다.
잘못된 매개변수를 최대한 일찍 발견하려면 빌더의 생성자와 메서드에서 입력 매개변수를 검사하고, build 메서드가 호출하는 생성자에서 여러 매개변수에 걸친 불변식을 검사해야 한다. 공격에 대비해 이런 불변식을 보장하려면 빌더로부터 매개변수를 복사한 후 해당 객체 필드들도 검사해야 한다. 검사에서 잘못된 점을 발견한다면 어떤 매개변수가 잘못되었는지 알려주는 메시지를 담아 IllegalArgumentException을 던지면 된다.
public Builder(String model) {
if (model == null || model.isEmpty()) {
throw new IllegalArgumentException("Model cannot be null or empty");
}
this.model = model;
}
public Builder color(String color) {
if (color == null || color.isEmpty()) {
throw new IllegalArgumentException("Color cannot be null or empty");
}
this.color = color;
return this;
}
public Builder year(int year) {
if (year < 1886 || year > 2100) { // 자동차가 처음 발명된 해 이후로 제한
throw new IllegalArgumentException("Year must be between 1886 and 2100");
}
this.year = year;
return this;
}
위 코드와 같이 매개변수에 대한 예외처리를 진행할 수 있다.
private Car(Builder builder) {
model = builder.model;
color = builder.color;
year = builder.year;
isElectric = builder.isElectric;
// 불변식 검사
if (model == null || model.isEmpty()) {
throw new IllegalArgumentException("Model cannot be null or empty");
}
if (color == null || color.isEmpty()) {
throw new IllegalArgumentException("Color cannot be null or empty");
}
if (year < 1886 || year > 2100) {
throw new IllegalArgumentException("Year must be between 1886 and 2100");
}
}
더하여 위 코드에서처럼 생성자에서 불변식을 검사하여, 최종 객체 생성 시 Builder에서 전달된 값들이 논리적으로 일관되는지 확인해야 한다.
💡 각 패턴 요약
| 패턴 명 | 방식 | 장점 | 단점 |
| 점층적 생성자 패턴 (telescoping constructor pattern) |
필수 매개변수와 선택적 매개변수를 받는 생성자를 필요한 경우에 맞게 각각 구현 | 매개변수들이 유효한지만 생성자에서 확인하면 일관성 유지 가능 | - 매개변수 개수가 많아지면 코드를 이해하기 어려움 - 타입이 같은 매개변수가 연달아 있을 시 클라이언트의 실수 유발 |
| 자바빈즈 패턴 (JavaBeans pattern) |
매개변수가 없는 생성자로 객체를 만든 후, 세터(setter) 메서드들을 호출해 매개변수의 값 지정 | 인스턴스를 만들기 쉽고, 읽기 쉬운 코드 작성 가능 | - 객체 하나를 만들려면 메서드를 여러 개 호출해야 하고, 객체가 완전히 생성되기 전까지는 일관성(consistency)이 무너진 상태 - 클래스를 불변으로 생성 불가능하며, 스레드 안정성을 위해 추가 작업 필요 |
| 빌더 패턴 (Builder pattern) |
필요한 객체를 직접 만드는 대신, 필수 매개변수만으로 생성자를 호출해 빌더 객체를 얻고, 일종의 세터 메서드들로 원하는 선택 매개변수들을 설정 | - 쓰기 쉽고, 읽기 쉬움 - 계층적으로 설계된 클래스와 함께 사용하기 좋음 |
- 객체를 생성하기 전에 빌더부터 구현해야 함 - 점층적 생성자 패턴보다 코드가 길어 매개변수가 많을수록 유용함 |
'이펙티브 자바' 카테고리의 다른 글
| 객체 생성과 파괴(2) - 정적 팩터리 메서드 단점 (0) | 2025.01.10 |
|---|---|
| 객체 생성과 파괴(1) - 정적 팩터리 메서드 장점 (0) | 2025.01.10 |