如何用一些设计模式替换复杂的条件? [英] How Can I Replace Complex If Condition With Some Design Pattern ?

查看:149
本文介绍了如何用一些设计模式替换复杂的条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我嵌套了条件如箭头

Suppose i have nested if condition like arrow

if()
{
   if()
      if()
        .....
        .....


}
else
{
}



如何用设计模式或一些优雅的方法替换上面的问题

i听说过有关规则引擎但却不知道如何实现


How can I replace above problem with design pattern or some elegant approach
i have heard something about rule engine but don't know how to implement

推荐答案

请参阅我对该问题的评论。这些技术与设计模式无关。



这太简单了。假设你有

Please see my comment to the question. Such techniques are not related to "design patterns".

This is way too simple thing. Suppose you have
if (conditionOne)
   if (conditionTwo)
      if (conditionTree)
          //...



严格相当于


It is strictly equivalent to

if (conditionOne && conditionTwo && conditionTree) // in exactly this order
   //...



请注意使用'&&',这与'&'不同。 '&&'优化冗余条件检查,与嵌套的if完全一样。与此相反,'&'将执行所有检查。如果这些条件是带有副作用的属性(或者它们可以起作用,如果我写了 conditionOne()而不是使用属性语法)。这就是为什么不建议在 getters 上创建具有副作用的属性;甚至不太建议在条件运算符中使用带副作用的函数的属性。 (我希望你明白什么是副作用:除了返回价值之外的东西)。



请参阅:

http://msdn.microsoft.com/en-us/library/2a723cdk.aspx [ ^ ],

< a href =http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx> http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx [< a href =http://msdn.microsoft.com/en-us/library/sbf85k1c.aspxtarget =_ blanktitle =New Window> ^ ]。



-SA


Note the use of '&&', which is not the same as '&'. '&&' optimizes out redundant condition check, exactly as with nested "if". In contrast to that, '&' will perform all the checks. Not only it would be worse for performance, if makes some difference in calculation if those conditions are properties with side effects (or they could functions, if I wrote conditionOne() instead of using the property syntax). That's why it is not recommended to create properties with side effect on getters; and even less recommended to use properties of functions with side effects in conditional operators. (I hope you understand what is "side effect": something except just returning the value).

Please see:
http://msdn.microsoft.com/en-us/library/2a723cdk.aspx[^],
http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx[^].

—SA


即使问题得到解答也接受了答案......

如果你真的有兴趣学习这些布尔的东西,我建议深入了解它的背景。



Eg你可以从这里开始: http://en.wikipedia.org/wiki/Boolean_algebra [ ^ ]



了解背景知识也避免像经常看到的那样写出愚蠢的staemanets:



Even the question is answered and an answer is accepted...
If you are really interested to learn these "boolean" stuff I suggest to dive into it's Background.

E.g. you can start here: http://en.wikipedia.org/wiki/Boolean_algebra[^]

To know the Background also avoids to write silly staemanets like one can see often:

bool theDecision= a && b;
if (theDecision == true) // silly to compare a boolean like this
{
    // this and that
}


这篇关于如何用一些设计模式替换复杂的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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