[英]How to create a class with a list of elements from another class without breaking the dependency injection rule?
我的课有几个领域。
public class Foo {
int firstCoef;
int secondCoef;
public Foo(String args){
this.firstCoef=Integer.parseInt(args[0]);
this.secondCoef=Integer.parseInt(args[1]);
}
}
因为我通过从.csv读取数据来创建此类的几个成员,所以以这种方式分配参数。 我还有另一个类管理Foo实例列表。 它通过从文件中读取一次创建整个列表,并将该列表用于计算。 在类构造函数中创建列表时,它使用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;
}
}
据我了解,这被认为是糟糕的设计,因为无法注入依赖项。 另外,很难测试。 如何在不使输入复杂化的情况下更改设计? 这两个类的唯一目标是最终能够执行计算。
您可以添加另一个图层,方法是添加一个类,执行从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));
}
}
}
然后在FooManger的构造函数中使用它:
public FooManager(FooParser parser, List<String[]> input) {
allFoos = parser.apply(input);
}
这样,您就可以将逻辑的另一部分放在单独的类中,并且更容易进行隔离测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.