728x90
Case : scale well to large numbers of optional parameters
-> static factories and contructors not good for this case
then how to solve this case?
The answer is : Builder
Traditionally programmers have used the 'telescoping constructor'
but, there have some problem
- Hard to write client code
- Harder to read it
and also you can say 'how about use JavaBeans'
but there are still have some issues.
- Inconsistent state partway through its construction
- Precludes the possibility of making as class immutable
Luckily, there is the 'Builder pattern'
Let's see how it works
- Client calls a constructor with all of the required parameters and gets a builder object
- Client calls setter-like methods on the builder object to set each optional parameter of interest
- The client calls a parameterless build method to generate the object, which typically immutable
Advantages of Builder pattern
- Simulates named optional parameters
- Well suited to class hierarchies
Summary
The builder pattern is a good choice when designing classes whose constructors or static factories would have more then a handful of parameters
728x90
반응형
'개인공부 > language' 카테고리의 다른 글
[JAVA] Effective JAVA - Item 4 : Enforce noninstantiability with a private constructor (0) | 2025.03.31 |
---|---|
[JAVA] Effective JAVA - Item 3 : Enforce the singleton property with a privateconstructor or an enum type (0) | 2025.03.24 |
[JAVA] Effective JAVA - Item 1 : Consider static factory methods instead of constructor (0) | 2025.03.01 |
[GO] 배열 선언하기 (0) | 2024.12.04 |
[GO] 에러 핸들링 방법 (1) | 2024.11.25 |