首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Item 二: Consider a builder when faced with many constructor parameters

2013-02-15 
Item 2: Consider a builder when faced with many constructor parametersTree buildTree(Builder? exte

Item 2: Consider a builder when faced with many constructor parameters
Tree buildTree(Builder<? extends Node> nodeBuilder) { ... }

?
10.??? The traditional Abstract Factory implementation in Java has been the Class object, with the newInstance method playing the part of the build method. The newInstance method always attempts to invoke the class’s parameterless constructor, which may not even exist. You don’t get a compile-time error if the class has no accessible parameterless constructor. Instead, the client code must cope with InstantiationException or IllegalAccessException at runtime, which is ugly and inconvenient. Also, the newInstance method propagates any exceptions thrown by the parameterless constructor, even though newInstance lacks the corresponding throws clauses. In other words, Class.newInstance breaks compile-time exception checking.


11.??? 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 performance critical situations.

?

12.??? 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.

?

13.??? 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.

热点排行