《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.

你可能感兴趣的:(java)