▪️Effective Java
조슈아 블로크 저
[2] Builder
자바빈즈 패턴의 세터(setter)
Builder pattern
public class ComplexObject {
// 모든 속성 불변으로 관리할 수 있다.
private final String width;
private final String height;
private final String color;
...
public static class Builder {
// 필수
private final String width;
private final String height;
// 선택 (초기값 설정)
private String color = "";
private String text = "";
...
public Builder(String width, String height) {
// validate code...
this.width = width;
this.height = height;
}
public Builder color(String color) {
// validate code...
this.color = color;
return this;
}
public Builder text(String text) {
// validate code...
this.text = text;
return this;
}
...
public ComplexObject build() {
// validate code...
return new ComplexObject(this);
}
}
// 불변 객체로 사용
// 일관성 확보
private ComplexObject(Builder builder) {
this.width = builder.width;
this.height = builder.height;
this.color = builder.color;
...
}
}[11] hashCode 재정의
Last updated