- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
一般来说,类构造函数应该接受的最大参数数量是多少?我正在开发一个需要大量初始化数据(目前有 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/
我正在为一个类(class)项目制作一个 C# 应用程序。我想确保一个字符串具有三个值之一。通常,在网络应用程序中,我会在客户端使用 javascript 进行验证。但是,这目前是一个控制台应用程序。
我注意到了 int i=10000000; boolean isPrime= false; while(!isPrime){ i++; Syst
一般来说,类构造函数应该接受的最大参数数量是多少?我正在开发一个需要大量初始化数据(目前有 10 个参数)的类。但是,带有 10 个参数的构造函数感觉不对。这让我相信我应该为每条数据创建一个 gett
改善网页加载时间的一种方法是内联其 css - 因为 css 会阻塞渲染。但是,内联 css 会阻止浏览器缓存它。因此,一般建议仅内联“小”css。 但是什么才算“小”呢?我在网上搜索了一些经验法则,
我正在尝试了解如何正确使用 Java 的执行器。我意识到将任务提交给 ExecutorService 有其自身的开销。但是,我很惊讶地看到它竟然这么高。 我的程序需要以尽可能低的延迟处理大量数据(股票
我读过几篇 GWT 开发人员博客,其中提到了一些“经验法则”,即如果生成的 JavaScript 代码达到 100 行或更多,最好自己编写 JavaScript(而不是通过 GWT 生成它) . 我的
最近我偶然发现了一个非常大的性能改进——我说的是 4 倍的改进——只需更改一行代码。我刚刚将 std::sort 调用更改为 concurrency_parallel 排序 // Get a cont
我在 javascript 中使用 setTimeout() 函数来允许在解析一些 xml 数据时显示一个显示“正在加载”的弹出窗口。我发现,在足够小的延迟值(低于 10 毫秒)下,在浏览器卡住一段时
Leonid 在他的书的第四章中写道:“...Module、Block 和 With。这些结构在 Mathematica Book 和 Mathematica Help 中有详细解释,所以我在这里简单
我是一名优秀的程序员,十分优秀!