执行此操作时,不要使用“if”|if(s == “value1”){...} else if(s == “value2”) { ...}

2022-09-01 21:29:22

根据反 if 运动,在我们的代码中不使用 ifs 是一种最佳做法。谁能告诉我是否有可能摆脱这段代码中的if?(switch也不是一个选项,关键是要去掉条件逻辑,而不是用类似的语言结构替换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#)


答案 1

这是一种方法... :)

delegate void DoStuff();

...

IDictionary<string, DoStuff> dict = new Dictionary<string, DoStuff>();
dict["foo"] = delegate { Console.WriteLine("some logic here"); };
dict["bar"] = delegate { Console.WriteLine("something else here"); };
dict["raboof"] = delegate { Console.WriteLine("of course I need more than just Writeln"); };
dict["foo"]();

答案 2

利用策略模式

在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();

推荐