首页 > 解决方案 > 如何在不污染代码的情况下从另一个具有大签名构造函数的 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);
    }

标签: java

解决方案


您可以使用构建器设计模式来避免在构造函数中传递过多的参数。当我们有太多参数要在构造函数中发送并且难以维护顺序时使用它。模板的片段如下所示。希望它能给你正确的见解。[1]:https ://i.stack.imgur.com/7y0sR.png


推荐阅读