简体   繁体   English

如何在不破坏依赖注入规则的情况下创建一个包含另一个类的元素列表的类?

[英]How to create a class with a list of elements from another class without breaking the dependency injection rule?

I have class that has several fields. 我的课有几个领域。

public class Foo {
 int firstCoef;
 int secondCoef;

 public Foo(String args){
  this.firstCoef=Integer.parseInt(args[0]);
  this.secondCoef=Integer.parseInt(args[1]);
 }
}

The arguments are assigned this way because I create several members of this class by reading data from .csv. 因为我通过从.csv读取数据来创建此类的几个成员,所以以这种方式分配参数。 I have another class that manages a list of Foo instances. 我还有另一个类管理Foo实例列表。 It creates the whole list at once by reading it from file and uses the list for calculation. 它通过从文件中读取一次创建整个列表,并将该列表用于计算。 When creating a list in class constructor, it uses new Foo(string) . 在类构造函数中创建列表时,它使用new Foo(string)

public class FooManager {
    protected List<Foo> allFoos = new ArrayList<Foo>();

    public FooManager(List<String[]> input) {
        String[] line;
        for (int lineNumber = 0; lineNumber < input.size(); lineNumber++) {
            line = input.get(lineNumber);
            allFoos.add(new Foo(line));
        }
    }

    public int calculate(int number) {
        int result = 0;
        for (Foo foo : allFoos) {
            result += Math.pow(number + foo.getFirstCoef(), foo.getSecondCoef());
        }
        return result;
    }
}

From what I understand, this is considered bad design because the dependencies can't be injected. 据我了解,这被认为是糟糕的设计,因为无法注入依赖项。 Also, it is hard to test. 另外,很难测试。 How could I change the design without complicating the input? 如何在不使输入复杂化的情况下更改设计? The only goal of both classes is to be able to perform the calculation in the end. 这两个类的唯一目标是最终能够执行计算。

You could add another layer, by adding a class that does the translation from the List to List: 您可以添加另一个图层,方法是添加一个类,执行从List到List的转换:

public class FooParser implements Function<String[], Foo> {

    public Foo apply(String[] input) 
        for (int lineNumber = 0; lineNumber < input.size(); lineNumber++) {
            String[] line = input.get(lineNumber);
            allFoos.add(new Foo(line));
        }
    }
}

And then use it in the constructor of FooManger: 然后在FooManger的构造函数中使用它:

public FooManager(FooParser parser, List<String[]> input) {
    allFoos = parser.apply(input);
}

This way you have another part of logic in separate class - and it is easier to test in isolation. 这样,您就可以将逻辑的另一部分放在单独的类中,并且更容易进行隔离测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM