`
pcpig
  • 浏览: 91340 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

《Effective java 2》Item 2: Consider a builder when faced with many constructor

阅读更多
Traditionally, programmers have used the telescoping constructor pattern.
In short, the telescoping constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it.

A second alternative when you are faced with many constructor parameters is
the JavaBeans pattern
1st.a may be in an inconsistent state partway through its construction.
2nd.precludes the possibility of making a class immutable

disadvantages  :
1st. In order to create an object, you must first create its builder. While the cost of creating the builder is unlikely to be noticeable in practice, it could be a problem in some performancecritical situations.
2nd. the Builder pattern is more verbose than the telescoping
constructor pattern, so it should be used only if there are enough parameters, say,four or more. But keep in mind that you may want to add parameters in the future.If you start out with constructors or static factories, and add a builder when the class evolves to the point where the number of parameters starts to get out of hand,
the obsolete constructors or static factories will stick out like a sore thumb. Therefore,it’s often better to start with a builder in the first place.

In summary, the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics