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

Traditionally, programmers have used the [b]telescoping constructor pattern.[/b]
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 [b]JavaBeans pattern[/b]
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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值