본문 바로가기
Theory/Design Pattern

Builder Pattern

by y.j 2022. 3. 29.
728x90

Builder Pattern

빌더패턴은 복잡한 객체의 구조를 어떻게 더 효율적이게 관리하며, 같은 구조여도 서로 다른 표현으로 객체를 생성 할 수 있을지에 대해서 다룬다.

복잡한 객체의 구조를 분리시켜 같은 구조이지만 서로 다른 표현으로 객체를 생성할 수 있을까?

문제점

위 그림과 같이 만약에 new ProductA1(), new ProductB1() 등.. 여러가지 클래스를 특정 Object에서 생성하는 경우 유연함이 떨어진다. 또한, Object도 정의된 생성자로만 객체 생성해야만 한다.

Solution

복잡한 object내부를 부분으로 나눠 build object내에서 create할 수 있도록 한다. 그래서 직접 new로 클래스를 생성하기 보다는 build내에서 instantiation하도록 한다.

public class Director {
    private Builder builder;
    private ComplexObject co;

    public Director(Builder builder) {
        this.builder = builder;
    }

    public String construct() {
        System.out.println("Director: Delegating constructing "
                    + "a complex object to a builder object.");
        builder.buildPartA();
        builder.buildPartB();
        co = builder.getResult();
        return "Hello World from " + co.getParts() + " objects!";
    }
}

Advantage

  • 컴파일 타임 dependencies를 회피 할 수 있다. 

       - 직접 instantiation하기 보다는 object를 builder에게 맡기기 때문이다.

  •  clinet가 단순해진다.

        - create하는 것을 build에 맡기기 때문에 상대적으로 client는 단순해 진다.

 

Disadvantage

  • 추가적인 level 도입되어야 한다.

      - builder object에 의존할 수 있도록 해주는 중간 class나 interface가 필요하다.

 

[전체 코드]

https://github.com/jKyounju/adapterPatterns/tree/master/src/BuilderPattern

728x90

'Theory > Design Pattern' 카테고리의 다른 글

Prototype Pattern  (0) 2022.04.23
Factory Method Pattern  (0) 2022.04.10
ABSTRACT FACTORY PATTERN  (0) 2022.03.27
ADAPTER PATTERN  (0) 2021.07.22
SINGLETON PATTERN  (0) 2021.07.20

댓글