做到这一点不使用"若" |如果(S =="值1"){...}否则,如果(S =="值2"){...} [英] do this without using an "if" | if(s == "value1"){...} else if(s == "value2") { ...}

查看:182
本文介绍了做到这一点不使用"若" |如果(S =="值1"){...}否则,如果(S =="值2"){...}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据抗如果广告系列它不是在我们的代码中使用IFS的最佳做法。谁能告诉我,如果有可能在这段代码,如果摆脱了? (开关也不能选择,的一点是去除条件逻辑,不能与类似的语言结构替换IFS

 如果(S ==富)
{
Writeln(一些逻辑,在这里);
}
,否则如果(S ==栏)
{
Writeln(别的东西在这里);
}
,否则如果(S ==raboof)
{
Writeln(当然,我需要的不仅仅是更多的Writeln);
}



(语言:Java或C#)


< DIV CLASS =h2_lin>解决方案

请使用策略模式的。



在Java术语:

 公共接口策略{
无效的execute();
}

公共类SomeStrategy实现战略{
公共无效的execute(){
的System.out.println(一些逻辑。);
}
}



您可以用如下:

 地图<弦乐,战略与GT;策略=新的HashMap<弦乐,战略与GT;(); 
strategies.put(strategyName1,新SomeStrategy1());
strategies.put(strategyName2,新SomeStrategy2());
strategies.put(strategyName3,新SomeStrategy3());

// ...

strategies.get(S).execute();


According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also not an option, The point is to remove the conditional logic, not replace ifs with similar language constructs)

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");
}

(language: Java or C#)

解决方案

Make use of the strategy pattern.

In Java terms:

public interface Strategy {
    void execute();
}

public class SomeStrategy implements Strategy {
    public void execute() {
        System.out.println("Some logic.");
    }
}

which you use as follows:

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

这篇关于做到这一点不使用&QUOT;若&QUOT; |如果(S ==&QUOT;值1&QUOT;){...}否则,如果(S ==&QUOT;值2&QUOT;){...}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆