我目前正在创建一个java程序,我想在满足两个条件后运行一个方法。因此,当这两种情况同时发生时,应该调用该方法。我能想到的处理它的唯一方法是我在下面添加的,但这似乎不是最佳方法。
这里无论先调用method1
还是method2
,下面的方法都会检查另一个条件是否已经满足,然后运行该方法。由于可能有一些方法依赖于两个以上的条件,是否有更清晰的方法来处理它?</p>
我的例子:
public class Test() {
private boolean condition1 = false;
private boolean condition2 = false;
public void method1(){
condition1 = true;
if(condition2){
run();
}
}
public void method2(){
condition2 = true;
if(condition1){
run();
}
}
public void run(){
//Is run when both conditions are true
}
}
最佳答案
Since there might be methods that depend on more conditions then two
根据上面的陈述,我想我可以假设您可能有两个以上的条件,也许有多个组合?在这种情况下,您不想验证 run
方法中的条件。
您可以有一个专门的方法根据需要应用所需的条件,如下所示:
public void runIfTheConditionsAreMet() {
if(condition1 && condition2) {
run();
}
}
这样,您将拥有一个专用方法来检查条件,并仅在必要时调用您的 run
方法,而无需在 method1
、method2 中重复代码
,您将有一个地方可以记录条件(如果需要)。
您的代码看起来会更干净一些,如下所示:
public void method1(){
condition1 = true;
runIfTheConditionsAreMet();
}
public void method2(){
condition2 = true;
runIfTheConditionsAreMet();
}
诗。即使您不打算有更多条件,我认为这个解决方案也能满足您的需求。
关于java - 满足多个条件时运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585267/