생성과 관련된 디자인 패턴으로 동일 프로세스를 거쳐 다양한 인스턴스를 만들때 사용
예제 클래스 - Book
package builder;
public class Book {
private Long id; // 필수
private String isbn; // 필수
private String title;
private String author;
private int pages;
private String category;
}
필수 인자를 받는 생성자를 정의한 후에 선택적 인자를 추가로 받는 생성자를
계속해서 정의
public Book(Long id, String isbn) {
this.id = id;
this.isbn = isbn;
}
public Book(Long id, String isbn, String title) {
this.id = id;
this.isbn = isbn;
this.title = title;
}
public Book(Long id, String isbn, String title, String author) {
this.id = id;
this.isbn = isbn;
this.title = title;
this.author = author;
}
//...else
Book book=new Book(1L, "isbn1234", "Design Pattern", "minjae An", 360, "CE");
Book book=new Book(1L, "isbn2134", "minjae An", "Desing Pattern", 360, "CE");
// wrong value to title and author(same String type)
setter
메서드로 각 속성의 값을 설정하는 방법 public Book(){}
public void setId(Long id) {
this.id = id;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setPages(int pages) {
this.pages = pages;
}
public void setCategory(String category) {
this.category = category;
}
Book.java
public class Book{
private Long id;
private String isbn;
private String title;
private String author;
private int pages;
private String category;
public static class BookBuilder{
...
}
}
Book.BookBuilder
public static class BookBuilder {
private Long id;
private String isbn;
private String title;
private String author;
private int pages;
private String category;
public BookBuilder(Long id, String isbn) {
this.id = id;
this.isbn = isbn;
}
public BookBuilder title(String title) {
this.title = title;
return this;
}
public BookBuilder author(String author) {
this.author = author;
return this;
}
public BookBuilder pages(int pages) {
this.pages = pages;
return this;
}
public BookBuilder category(String category) {
this.category = category;
return this;
}
public Book build() {
Book book = new Book();
book.id = this.id;
book.isbn = this.isbn;
book.author = this.author;
book.title = this.title;
book.pages = this.pages;
book.category = this.category;
return book;
}
}
Book book = new Book.BookBuilder(1L, "isbn1234")
.author("minjae An")
.pages(360)
.category("CE")
.title("Design Pattern")
.build();
자바의 라이브러리로 어노테이션을 기반으로 코드를 자동으로 완성해주는 기능 제공
@Getter
@Builder //builder 자동 생성
public class LombokBook{
private Long id;
private String isbn;
private String title;
private String author;
private int pages;
private String category;
}
Lombok의 @NonNull
어노테이션을 이용하면 해당 필드에 대해 null check를 해준다.
@Getter
@Builder
public class LombokBook{
@NonNull
private Long id;
@NonNull
private String isbn;
private String title;
private String author;
private int pages;
private String category;
}