根据反if运动,最好的做法是在我们的代码中不要使用if。谁能告诉我是否有可能摆脱这段代码中的if?(切换也不是一种选择, 重点是删除条件逻辑,而不是用类似的语言构造替换ifs )
if(s == "foo") { Writeln("some logic here"); } else if(s == "bar") { Writeln("something else here"); } else if(s == "raboof") { Writeln("of course I need more than just Writeln"); }
(语言:Java或C#)
利用策略模式。
用Java术语:
public interface Strategy { void execute(); } public class SomeStrategy implements Strategy { public void execute() { System.out.println("Some logic."); } }
使用方法如下:
Map<String, Strategy> strategies = new HashMap<String, Strategy>(); strategies.put("strategyName1", new SomeStrategy1()); strategies.put("strategyName2", new SomeStrategy2()); strategies.put("strategyName3", new SomeStrategy3()); // ... strategies.get(s).execute();