Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 몰디브
- 헤리턴스아라
- SpringSecurity
- java
- 소프트웨어장인정신
- 자바
- 주간회고
- 신혼여행
- 2022회고
- 메가테라
- jvm
- 상속
- Spring
- http 완벽 가이드
- HTTP 완벽가이드
- http
- 포트폴리오
- leetcode
- 이펙티브자바
- 부트캠프
- 클로저
- html
- CORS
- 취업회고
- 바닐라코딩
- css
- 자바스크립트
- Hibernate Reactive
- til
- JavaScript
Archives
- Today
- Total
codingBird
[이펙티브 자바] - Item 2 생성자에 매개변수가 많다면 빌더를 고려하라. 본문
Item2 - 생성자에 매개변수가 많다면 빌더를 고려하라.
점층적 생성자 패턴은 매개변수 개수가 많아지면 클라이언트 코드를 작성하거나 읽기 어려워진다.
자바빈즈 패턴은 객체의 일관성이 깨져 오류가 발생하기 쉽다.
필수 인자와 필수 인자가 아닌 값들을 필드로 가지는 객체를 생성할 때 명명된 선택적 매개변수를 흉내낸 빌더를 사용해 유연하게 생성해보자.
public class Product {
private String name;
private int price;
private String color;
private String size;
private Product(Builder builder) {
this.name = builder.name;
this.price = builder.price;
this.color = builder.color;
this.size = builder.size;
}
// getters
// ...
public static class Builder {
private String name;
private int price;
private String color;
private String size;
public Builder(String name, int price) {
this.name = name;
this.price = price;
}
public Builder color(String color) {
this.color = color;
return this;
}
public Builder size(String size) {
this.size = size;
return this;
}
public Product build() {
return new Product(this);
}
}
}
Product product = new Product.Builder("phone", 1000)
.color("black")
.size("large")
.build();
'JAVA' 카테고리의 다른 글
Spring Application - CORS 설정 - 2 (0) | 2023.07.11 |
---|---|
Spring Application - CORS 설정 - 1 (0) | 2023.07.11 |
[이펙티브 자바] - Item 1 생성자 대신 정적 팩터리 메서드를 고려하라 (0) | 2023.04.14 |
모든 프로그래머가 알아야 하는 JVM - Runtime Data Area (0) | 2022.09.10 |
Favor composition over inheritance. (0) | 2022.09.06 |