gpt4 book ai didi

java - 构造函数参数 - 经验法则

转载 作者:IT老高 更新时间:2023-10-28 20:43:18 28 4
gpt4 key购买 nike

一般来说,类构造函数应该接受的最大参数数量是多少?我正在开发一个需要大量初始化数据(目前有 10 个参数)的类。但是,带有 10 个参数的构造函数感觉不对。这让我相信我应该为每条数据创建一个 getter/setter。不幸的是,getter/setter 模式不会强制用户输入数据,没有它,对象的特征是不完整的,因此是无用的。想法?

最佳答案

有了这么多参数,是时候考虑Builder pattern了.创建一个包含所有这些 getter 和 setter 的构建器类,并使用 build() 方法返回您真正尝试构建的类的对象。

示例:

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);
}
}
}

在您的客户端代码中:

ReallyComplicatedClass c = new ReallyComplicatedClass.Builder()
.int1(myInt1)
.str2(myStr2)
.build();

参见 Effective Java Reloaded 的第 7-9 页[pdf],Josh Bloch 在 JavaOne 2007 上的演讲。(这也是 Effective Java 2nd Edition 中的第 2 项,但我手边没有,所以无法引用。)

关于java - 构造函数参数 - 经验法则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/730201/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com