我必须编写一个用于保存计算结果的 Java 对象。结果包含大量字段,根据所使用的算法类型,可能会或可能不会设置这些字段。例如:
class EquityValuationResult {
private ValuationAlgorithm algorithm;
private int yield;
private double curve;
private double meanValue;
private double probability;
private int standardDeviation;
private boolean approximateValue;
......
//Getter and Setters
}
Run Code Online (Sandbox Code Playgroud)
对于不同的 ValuationAlgorithm,这些属性的内容可能不同。例如,如果算法是A,yield 和probability 会包含计算值,其余的将为null;如果算法是 B,standardDeviation 和 curve 将包含结果,其余的将为 null 等。规则非常复杂,例如,如果 approcimateValue 为 true,则某些值将被覆盖等。因此,所有这些属性必须在一个类中,因为它们在逻辑上是一个结果。
另一种方法是使用 Map
class EquityValuationResult {
private final String YIELD = "yield";
private final String CURVE = "curve";
........
private ValuationAlgorithm algorithm;
private final Map<String, Object> result = new HashMap<String, Object>();
// Getter and Setters
}
Run Code Online (Sandbox Code Playgroud)
但是如果我这样做,getter 和 setter 必须将值从 Object 转换为相应的数据类型。我还必须定义那些常量并将它们用作映射的键,这看起来太麻烦了。
您认为哪种方式更好?有没有其他更好的方法来做到这一点?
编辑:忘了提到,由于限制,为每个计算类型创建单独的类不是一个选项。我必须使用一个类。
如果允许您创建助手或其他东西,请忘记地图示例。在这种限制下,我可能会编写一个枚举作为帮助器/类型来识别,也许还编写一个映射器来保留基于类型的顺序。
作为结果类中的辅助方法也许:
public double[] getCalcValues(){
switch (calculationType){
case A:
// do something
return null;
case B:
// do something
return null;
default:
throw new RuntimeException("Not Really Possible");
}
}
Run Code Online (Sandbox Code Playgroud)
由于 CaclulationType 的枚举类型,这有望成为可能。例如:
public enum CalculationType {
A("A"), B("B");
final String calcType;
private CalculationType(String calcType) {
this.calcType = calcType;
}
// ... other enum stuff
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我可能会将枚举设为 Final 进行实例化,并使用静态辅助方法进行 cal 值提取,并故意将 getter 保留在主类之外,除非有人可以取消 null 值。我为枚举留下了一个吸气剂,以防万一您在其他地方需要它,如果不需要,那么我想我也会将其省略。
public class Result {
final CalculationType calculationType;
private int yield;
private double curve;
private double meanValue;
private double probability;
private int standardDeviation;
public Result(CalculationType calculationType) {
this.calculationType = calculationType;
}
public CalculationType getCalculationType() {
return calculationType;
}
public double[] getCalcValues(){
switch (calculationType){
case A:
// do something
return null;
case B:
// do something
return null;
default:
throw new RuntimeException("Not Really Possible");
}
}
// Only include setters below, force users to use getCalcValues as an extraction class
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7352 次 |
| 最近记录: |