[英]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.