gpt4 book ai didi

java - 如何更改使用许多 if 语句按名称选择类的代码?

转载 作者:行者123 更新时间:2023-12-02 05:50:56 25 4
gpt4 key购买 nike

我正在开发一个程序来模拟 RLC 电路。该程序根据电路类型和源类型(RLC、LC、RC、正弦波、DC、方波...)进行一些特定计算,随后将其添加到图表中。

下面的代码按照我需要的方式工作,但是我的老师告诉我,如果我为每个案例创建一个单独的类会更好,因为太多的 if 语句不好。

if(scheme == "RLC"){
beta = R / (2*L);
omega0Square = 1/ (L*C);

//Resonant
if (omega * omega == omega0Square
&& beta >= Math.sqrt(omega0Square) / Math.sqrt(2)){

chargeAmp = U0 / (L*2*beta*Math.sqrt(omega0Square - beta*beta));
fi = Math.atan(Math.sqrt(omega0Square-2*beta*beta)/beta);
}

//Non-resonant
else{
omegasDifference = (omega0Square - omega * omega);
fi = Math.atan(2 * beta * omega / omegasDifference);
chargeAmp = U0/(L*Math.sqrt(omegasDifference * omegasDifference
+ 4 * beta * beta * omega * omega));
}

intensity = chargeAmp*omega* Math.cos(omega*time-fi);
rU = R * intensity;
cQ = chargeAmp*Math.sin(omega*time-fi);
lE = L*intensity*intensity/2;
}
if(scheme == "LC"){

}
if(scheme == "RC"){

}
if(scheme == "R"){

}
if(scheme == "L"){

}
if(scheme == "C"){

}
if(scheme == "Non"){

}

如果我为每种情况创建一个类,我以后如何管理它们,并在不使用 if 语句的情况下调用它们?我想到了这样的事情:

String name;
name variable = new name();

这可能吗?或者有更好的办法吗?

最佳答案

使用接口(interface)和 factory pattern

创建一个类来保存值(R、L、C)

public class RLCHolder {
double rValue;
double lValue;
double cValue;
//Setter and Getters
}

创建界面

public interface CircuitCalculator {
public double calculate(RLCHolder rlcHolder);
}

现在实现接口(interface)

public class RLCCircuitCalculator implements CircuitCalculator {

@Override
public double calculate(RLCHolder rlcHolder) {
// Do you Math and Return
return 0;
}

}

像这样添加其他电路的实现,例如。

LCCircuitCalculatorRCCircuitCalculator

现在创建工厂方法并调用计算方法

public class Calculator {

// factory method
public static CircuitCalculator getCircuitCalculator(String circuitName){
CircuitCalculator circuitCalculator = null;
if (circuitName.equals("RLC")){
circuitCalculator = new RLCCircuitCalculator(); // You can cache if you dont maintain state
}else if (circuitName.equals("LC")){
// return LC object
}//add your implementation..
return circuitCalculator;
}


public static void main(String args[]){
RLCHolder rlcHolder = new RLCHolder();
double result = Calculator.getCircuitCalculator("RLC").calculate(rlcHolder);
}

}

关于java - 如何更改使用许多 if 语句按名称选择类的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com