从Java中不同方法中的条件内部引用开关的每种情况 [英] referencing each case of a switch from a conditional inside a different method in java
问题描述
我正在实现一些使用switch语句区分不同情况的方法:
I am implementing some methods which use switch statements to distinguish between different cases:
private void doThis(){
switch(command){
case on: {status = doCalculationsA; break;}
case off: {status = doCalculationsB; break;}
case idle: {status = doCalculationsC; break;}
case stdby:{status = doCalculationsD; break;}
}
}
当在业务逻辑中进一步深入时,我在需要doThis()功能的其他方法中调用doThis()时,以上方法工作正常.
The above works fine, when, further down the business logic, I call doThis() inside other methods which need the doThis() functionality.
但是,此刻我有点困惑如何将上述开关的每种情况所施加的其他条件/限制纳入其中.
However, at this moment I am a bit confused how to incorporate other conditions/restrictions posed on each case of the above switch.
我的意思是,当我在"bigerOperation()"中调用doThis()时,我需要针对doThis()函数所属的每种开关情况应用新条件:
I mean, when I call doThis() within say biggerOperation(), I have new conditions that need to be applied against each case of the switch belonging in the doThis() function:
示例逻辑:
biggerOperation(){
doThat();
doTheOther();
if(somethingIsTrue){
execute "case: on" of doThis()
}
else if(somethingElseIsTrue){
execute "case: off" of doThis()
}
else if(aThirdThingIsTrue){
execute "case: idle" of doThis()
}
else if(aFourthThingIsTrue){
execute "case: stdby" of doThis()
}
}
到目前为止,我还无法找到一种优雅,干净,紧凑的方式来执行此操作.也许有什么想法吗?如何明确针对每种情况下的开关?我可以使用一个新的开关来实现该条件逻辑吗?
I have not been able to figure out an elegant, clean and compact way to do this as of now. Are there any ideas perhaps? How can I explicitly target each case of a switch? Could I use a new switch to implement that conditional logic?
欢迎提出任何建议.非常感谢您的帮助.
Any suggestions are welcome. Much appreciate your help.
推荐答案
使用命令模式将命令枚举重构为类.
Refactor your command enum to classes using the Command pattern.
这篇关于从Java中不同方法中的条件内部引用开关的每种情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!