用模式替换 if else 语句 [英] Replacing if else statement with pattern
问题描述
我有一个 if else 语句,它可能会在不久的将来增长.
I have a if else statement which might grow in the near future.
public void decide(String someCondition){
if(someCondition.equals("conditionOne")){
//
someMethod("someParameter");
}else if(someCondition.equals("conditionTwo")){
//
someMethod("anotherParameter");
}
.
.
else{
someMethod("elseParameter");
}
}
既然这看起来已经很乱了,我想如果我能在这里应用任何设计模式会更好.我研究了策略模式,但我不确定这是否会减少这里的其他条件.有什么建议吗?
Since, this is already looking messy, I think it would be better if I can apply any design patterns here. I looked into Strategy pattern but I am not sure if that will reduce if else condition here. Any suggestions?
推荐答案
这是一个经典的Replace Condition使用命令的调度器在重构为模式一书中.
This is a classic Replace Condition dispatcher with Command in the Refactoring to Patterns book.
基本上,您为旧的 if/else 组中的每个代码块创建一个 Command
对象,然后为这些命令创建一个 Map,其中键是您的条件字符串
Basically you make a Command
object for each of the blocks of code in your old if/else group and then make a Map of those commands where the keys are your condition Strings
interface Handler{
void handle( myObject o);
}
Map<String, Handler> commandMap = new HashMap<>();
//feel free to factor these out to their own class or
//if using Java 8 use the new Lambda syntax
commandMap.put("conditionOne", new Handler(){
void handle(MyObject o){
//get desired parameters from MyObject and do stuff
}
});
...
然后代替您的 if/else 代码:
Then instead of your if/else code it is instead:
commandMap.get(someCondition).handle(this);
现在,如果您以后需要添加新命令,只需添加到哈希中即可.
Now if you need to later add new commands, you just add to the hash.
如果您想处理默认情况,您可以使用 Null Object
模式来处理条件不在 Map 中的情况.
If you want to handle a default case, you can use the Null Object
pattern to handle the case where a condition isn't in the Map.
Handler defaultHandler = ...
if(commandMap.containsKey(someCondition)){
commandMap.get(someCondition).handle(this);
}else{
defaultHandler.handle(this);
}
这篇关于用模式替换 if else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!