빌더패턴 (1)

Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼  Builder 패턴은 Creational 패턴에 속한다.   


빌더 패턴은 팩토리 메소드 또는 추상 팩토리 패턴의 문제점을 해결하기 위해 나온 패턴이다. 팩토리 메소드 또는 추상 팩토리 패턴에는 객체가 많은 속성을 가지고 있을 경우 두가지 중요한 문제가 발생한다. 

 

첫 째로, 클라이언트가 팩토리 클래스로 넘겨주는 인자가 많아지게되면( 팩토리가 많은 속성을 가지고 있으면 이에 대해 설정을 하기위해 많은 인자를 받아야 한다 ) 잘못된 인자를 넘겨주는 일도 빈번하게 일어날 뿐 아니라 관리하기도 힘들어진다.

둘째로, 몇몇 인자들은 optional일 수 있지만 팩토리 패턴에서는 모든 인자를 넘겨주어야 한다. ( optional 인자는 null로 넘긴다. 이건 귀찮은 일이다. )

 

빌더 패턴은 단계별로 객체를 생성하고 마지막 객체를 반환하는 메소드를 제공함으로써 위와 같은 문제들을 해결해준다. 


 

Builder Pattern Structure



 


패턴의 목적 ( Intent ) : 

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

 복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴


패턴이 나오게 된 동기 ( Motivation ) :


 

예 를들어 RTF포맷 형태의 파일을 ASCIIText나 TeXText 또는 다른 TextWidget의 형태로 변환하는 프로그램을 만든다고 하자. 이때 변환되어 나오는 포맷을 쉽게 추가할 수 있어야 할 것이다. 그래서 나온 패턴이 바로 이 빌더 패턴이다. 위 다이어그램에서 각각의 컨버터 클래스들은 모두 builder이며 reader는 director라 한다. 그리고 변형되어 나오는 Text객체들은 product라고 보면 된다. 

 


유용성 ( Applicability ) :

Use the Builder pattern when
· the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.
· the construction process must allow different representations for the object that's constructed.

 

등장 인물 ( Participants ) : 

· Builder
o specifies an abstract interface for creating parts of a Product object.
· ConcreteBuilder
o constructs and assembles parts of the product by implementing the Builder interface.
o defines and keeps track of the representation it creates.
o provides an interface for retrieving the product.
· Director
o constructs an object using the Builder interface.
· Product
o represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled.
o includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.


원리 ( Collaborations ) :

· The client creates the Director object and configures it with the desired Builder object.
· Director notifies the builder whenever a part of the product should be built.
· Builder handles requests from the director and adds parts to the product.
· The client retrieves the product from the builder.

 

The following interaction diagram illustrates how Builder and Director cooperate with a client.

 

 


패턴 사용의 장단점 ( Consequences ): 

Here are key consequences of the Builder pattern:


1. It lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product. It also hides how the product gets assembled. Because the product is constructed through an abstract interface, all you have to do to change the product's internal representation is define a new kind of builder.


2. It isolates code for construction and representation. The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented. Clients needn't know anything about the classes that define the product's internal structure; such classes don't appear in Builder's interface. Each ConcreteBuilder contains all the code to create and assemble a particular kind of product. The code is written once; then different Directors can reuse it to build Product variants from the same set of parts.
In the earlier RTF example, we could define a reader for a format other than RTF, say, an SGMLReader, and use the same TextConverters to generate ASCIIText, TeXText, and TextWidget renditions of SGML documents.


3. It gives you finer control over the construction process. Unlike creational patterns that construct products in one shot, the Builder pattern constructs the product step by step under the director's control. Only when the product is finished does the director retrieve it from the builder. Hence the Builder interface reflects the process of constructing the product more than other creational patterns. This gives you finer control over the construction process and consequently the internal structure of the resulting product. 

 

관련 패턴들 : 

 Abstract Factory is similar to Builder in that it ​constructs too may complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract Factory's emphasis is on families of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory pattern is concerned, the product gets returned immediately.
A Composite is what the builder often builds.

 

추가 정보 :     

  • Sometimes creational patterns are complementory: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.

 

 

출처 :  http://sourcemaking.com/design_patterns/builder

Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )  

http://www.journaldev.com/1425/builder-design-pattern-in-java