빌더 패턴(Builder Pattern)

Minjae An·2023년 10월 14일
0

설계패턴

목록 보기
1/7
post-thumbnail

빌더 패턴이란?

생성과 관련된 디자인 패턴으로 동일 프로세스를 거쳐 다양한 인스턴스를 만들때 사용

  • 객체 생성 패턴
  • 생성자의 인자가 많은 경우 유용
  • 생성자의 인자들 중 필수적 인자와 선택적 인자가 혼합되어 있는 경우
  • Immutable 객체(불변 객체)를 생성하고 싶은 경우

예제 클래스 - Book

package builder;

public class Book {
    private Long id; // 필수
    private String isbn; // 필수
    private String title;
    private String author;
    private int pages;
    private String category;
}

점층적 생성자 패턴(Telescoping Constructor)

필수 인자를 받는 생성자를 정의한 후에 선택적 인자를 추가로 받는 생성자를
계속해서 정의

필수적 인자 생성자

    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)
  • 가독성이 떨어진다.

JavaBeans 패턴

  • 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;
    }
  • 가독성은 향상되나 immutable object를 만들 수 없음

Builder 패턴

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;
        }
    }
  • 가독성 개선
  • 메서드 체이닝
  • Immutable 객체 생성
Book book = new Book.BookBuilder(1L, "isbn1234")
                .author("minjae An")
                .pages(360)
                .category("CE")
                .title("Design Pattern")
                .build();

Lombok @Builder

Lombok?

자바의 라이브러리로 어노테이션을 기반으로 코드를 자동으로 완성해주는 기능 제공

@Getter
@Builder //builder 자동 생성
public class LombokBook{
	private Long id;
    private String isbn;
    private String title;
    private String author;
    private int pages;
    private String category;
}

Mandatory 필드

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;
}
profile
도전을 성과로

0개의 댓글