java - 如何在不污染代码的情况下从另一个具有大签名构造函数的 Java 类中获取数据?
问题描述
我正在设计一个小项目,它简化了事情,看起来像这样
首先,我有一个从文件加载数据的类:
public class Data{
//private variables here
public Input(File file, other parameters..){
//load files
}
// getters for private variables here
}
然后我有一个算法类,它应该使用类 Data 上加载的数据:
public boolean Algorithm {
public boolean foo {
//initialize something
return recursiveAlgo(//parameters that would come from the Data class);
}
public boolean recursiveAlgo(//parameters..){
return something;
}
}
我想解决的问题是:我想使用通过de getter加载到Data类中的数据,但不使用构造函数:Input input = new Input(File file, other parameters)
因为它有很多参数,并且这些参数必须经过递归调用,导致他们要有一个大签名。如何访问存储在 Data 类中的数据,而不会污染我的 Algorithm 类?
我想要这样的东西:
public boolean Algorithm {
//Input input = new Input(File file, other parameters..); >not doing this<
//Input input = new Input(); >maybe something like this<
int row = input.getRow();
int col = input.getCol();
// so on..
public boolean foo {
//initialize something
return recursiveAlgo(//parameters that would come from the Data class);
}
解决方案
您可以使用构建器设计模式来避免在构造函数中传递过多的参数。当我们有太多参数要在构造函数中发送并且难以维护顺序时使用它。模板的片段如下所示。希望它能给你正确的见解。[1]:https ://i.stack.imgur.com/7y0sR.png
推荐阅读
- java - 使用 JAVA 和正则表达式查找 URL 的一部分
- ios - 已下载 PDF 文件但找不到
- google-colaboratory - google colab 是否永久更改文件
- swipe - ios 13 中的平移事件未按预期运行
- c# - 从阿拉伯语单词的第一个字符串中删除“ال”或“اَلْ”或“الْ”或“اَل”
- c - 如何从 C 程序连接到 IBM Db2 Event Store?
- azure-devops - 如何将更多测试与 azure devops 中的测试用例相关联
- json - TypeError: errorResponse.json is not a function - 试图将保留响应删除为 Json 但仍然面临问题
- autocomplete - 如何在 emacs 中使用 ELPY 进行自动完成工作?
- python-3.x - 关于给定示例中 numpy 中的数组索引