天天看點

Read Notes:[Effective Java] Consider a builder when faced with many constructor parameters

The Telescoping Constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it.

The JavaBeans pattern is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction. The JavaBeans pattern precludes the possibility of making a class immutable.

The Builder pattern simulates named optional parameters as found in Ada and Python. (builder pattern must first create its builder.  And it is more verbose than the telescoping constructor pattern.)

   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. Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern, and builders are much safer than JavaBeans.

繼續閱讀