본문 바로가기
프로그래밍/디자인 패턴(프로그래밍)

[Design Pattern]Builder Pattern이란?

by 그래도동 2019. 1. 17.
728x90
반응형

Builder Pattern이란?

 factory pattern이나 abstract factory pattern과 비슷하다.

이 두 패턴은 중대한 문제점이 있다.


factory pattern / abstract factory pattern 문제점 3가지

 - 호출하는 클래스로부터 많은 인자(파라메터)들이 전달된다. -> 에러발생이 많아질 수 있다. 인자들의 type을 정확히 맞추기 어렵기 때문이다.

 - 몇몇 파라메터들을 보내고 싶지만 모든 인자를 전송해야한다.

 - 생성시키는 객체가 많은 정보를 필요로 한 경우(파라메터가 많다 = 생성되어야 하는 객체가 무겁다) 만들기가 복잡해진다.


Builder Pattern은 파라메터가 많던지 적던지 일관성있게 차례차례 제공해준다.


예제

public class Product {

    // parameters
    private String name;
    private int price;

    // optional parameter
    private boolean isSell;

    public String getName() {
        return this.name;
    }

    public int getPrice() {
        return this.price;
    }

    public boolean isSellEnabled() {
        return isSell;
    }

    // argument -> ProductBuilder instance.
    private Product(ProductBuilder builder) {
        this.name = builder.name;
        this.price = builder.price;
        this.isSell = builder.isSell;
    }

    public static class ProductBuilder {
        private String name;
        private int price;
        private boolean isSell;

        public ProductBuilder(String name, int price) {
            this.name = name;
            this.price = price;
        }

        public ProductBuilder setIsSellEnabled(boolean isSell) {
            this.isSell = isSell;
            return this;
        }

        public Product build() {
            return new Product(this);
        }

    }
}
public class main {
    public static void main (String[] args) {
        Product p1 = new Product.ProductBuilder("test상품", 10000).setIsSellEnabled(true).build();
    }
}


Reference

 https://blog.seotory.com/post/2017/09/java-builder-pattern

728x90
반응형

댓글