构造函数参数 - 拇指规则 [英] Constructor Parameters - Rule of Thumb
问题描述
有了很多参数,现在是考虑 Builder模式。创建一个包含所有这些getter和setter的构建器类,并使用一个build()方法返回一个您真正想要构建的类的对象。
例如:
public class ReallyComplicatedClass {
private int int1;
private int int2;
private String str1;
private String str2;
// ...等等
//注意,构造函数是私有的
private ReallyComplicatedClass(Builder builder){
//从构建器$ b中设置所有这些变量$ b}
public static class Builder {
private int int1;
private int int2;
private String str1;
private String str2;
//等等
public Builder(/ *必需参数在这里* /){
//设置必需参数
}
public Builder int1(int newInt) {
int1 = newInt;
返回这个;
}
// ...所有可选参数的setter,所有返回'this'
public ReallyComplicatedClass build(){
return new ReallyComplicatedClass(this);
}
}
}
在您的客户端代码中:
ReallyComplicatedClass c = new ReallyComplicatedClass.Builder()
.int1(myInt1)
.str2(myStr2 )
.build();
请参阅有效的Java重新加载 [pdf] Josh Bloch在JavaOne 2007上的演讲(这也是有效的Java第2版,但我没有方便,所以我不能引用它。)
In general, what is the maximum number of parameters a class constructor should accept? I'm developing a class that requires a lot of initialization data (currently 10 parameters). However, a constructor with 10 parameters doesn't feel right. That leads me to believe I should create a getter/setter for each piece of data. Unfortunately, the getter/setter pattern doesn't force the user to enter the data and without it characterization of the object is incomplete and therefore useless. Thoughts?
With that many parameters, it's time to consider the Builder pattern. Create a builder class which contains all of those getters and setters, with a build() method that returns an object of the class that you're really trying to construct.
Example:
public class ReallyComplicatedClass {
private int int1;
private int int2;
private String str1;
private String str2;
// ... and so on
// Note that the constructor is private
private ReallyComplicatedClass(Builder builder) {
// set all those variables from the builder
}
public static class Builder {
private int int1;
private int int2;
private String str1;
private String str2;
// and so on
public Builder(/* required parameters here */) {
// set required parameters
}
public Builder int1(int newInt) {
int1 = newInt;
return this;
}
// ... setters for all optional parameters, all returning 'this'
public ReallyComplicatedClass build() {
return new ReallyComplicatedClass(this);
}
}
}
And in your client code:
ReallyComplicatedClass c = new ReallyComplicatedClass.Builder()
.int1(myInt1)
.str2(myStr2)
.build();
See pages 7-9 of Effective Java Reloaded [pdf], Josh Bloch's presentation at JavaOne 2007. (This is also item 2 in Effective Java 2nd Edition, but I don't have it handy so I can't quote from it.)
这篇关于构造函数参数 - 拇指规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!