在java中使用数百个if-else实现业务规则的设计模式

在java中使用数百个if-else实现业务规则的设计模式,java,if-statement,design-patterns,specification-pattern,Java,If Statement,Design Patterns,Specification Pattern,我必须用下面数百行代码来实现某些业务规则 if this then this else if then this . . // hundreds of lines of rules else that 我们是否有任何设计模式可以有效地实现这一点或重用代码,以便将其应用于所有不同的规则。 我听说规范模式创建了如下内容 public interface Specification { boolean isSatisfiedBy(Object o); Spe

我必须用下面数百行代码来实现某些业务规则

if this
      then this
else if
      then this
.
. // hundreds of lines of rules
 else
      that
我们是否有任何设计模式可以有效地实现这一点或重用代码,以便将其应用于所有不同的规则。 我听说规范模式创建了如下内容

public interface Specification {

boolean isSatisfiedBy(Object o);

Specification and(Specification specification);

Specification or(Specification specification);

Specification not(Specification specification);
}


public abstract class AbstractSpecification implements Specification {

public abstract boolean isSatisfiedBy(Object o);

public Specification and(final Specification specification) {
 return new AndSpecification(this, specification);
}

public Specification or(final Specification specification) {
 return new OrSpecification(this, specification);
}

 public Specification not(final Specification specification) {
 return new NotSpecification(specification);
}
}
然后是Is,And,Or方法的实现,但我认为这不能避免我写if-else(可能是我的理解不正确)

有没有最好的方法来实现包含这么多if-else语句的业务规则

编辑:只是一个示例。a、B、C等都是类的属性。除此之外,还有许多类似的其他规则。我想为此编写一个通用代码

    If <A> = 'something' and <B> = ‘something’ then
    If <C> = ‘02’ and <D> <> ‘02’ and < E> <> ‘02’  then
        'something'
    Else if <H> <> ‘02’ and <I> = ‘02’ and <J> <> ‘02’  then
        'something'
    Else if <H> <> ‘02’ and <I> <> ‘02’ and <J> = ‘02’  then
        'something'
    Else if <H> <> ‘02’ and <I> = ‘02’ and <J> = ‘02’  then 
        'something'
    Else if <H> = ‘02’ and <I> = ‘02’ and <J> <> ‘02’  then 
        'something'
    Else if <H> = ‘02’ and <I> <> ‘02’ and <J> = ‘02’  then 
        'something'
    Else if <H> = ‘02’ and <I> = ‘02’ and <J> = ‘02’  then:
        If <Q> = Y then
            'something'
        Else then 
            'something'
Else :
Value of <Z>
如果='something'和='something',那么
如果='02'和'02'以及'02',则
“有东西”
否则,如果'02'和='02'和'02',则
“有东西”
否则,如果'02'和'02'和='02',则
“有东西”
否则,如果'02'和='02'和='02',则
“有东西”
否则如果='02'和='02'和'02',则
“有东西”
如果Else为'02'和'02'并为'02',则
“有东西”
否则,如果='02'和='02'和='02',则:
如果=Y,则
“有东西”
否则
“有东西”
其他:
价值

类似规则引擎的东西可能会有所帮助。这不是一个设计模式,所以这可能不是你想要的答案。但是IMO,你应该考虑一下。这里有一篇关于的精彩文章。

您可以使用或

命令模式可用于替换笨重的开关/if块,这些块在添加新选项时会无限增长

public interface Command {
     void exec();
}

public class CommandA() implements Command {

     void exec() {
          // ... 
     }
}
// etc etc
然后构建一个
Map
对象并用命令实例填充它:

commandMap.put("A", new CommandA());
commandMap.put("B", new CommandB());
然后,您可以将if/else if链替换为:

commandMap.get(value).exec();

工厂模式中您将您的if/开关包含在一个工厂中,该工厂负责处理丑陋问题并隐藏大量的if

战略模式在这里可能很有用。请检查

设计模式可以帮助您提高代码的可读性或提高代码的可维护性,但是如果您确实需要评估这些数量的条件,则无法避免使用if语句

我会从另一个角度考虑这个问题(例如:我真的需要一百个条件语句来解决这个问题吗?),我会尝试改变或改进


可以提供一些帮助,因为您可以通过编程方式创建一个表示每个IF语句的字符串,并使用此工具计算结果,但您仍然需要解决与每个条件相关的特定逻辑的执行相关的问题。

一个简单的python策略演示:

class Context(object):
  def __init__(self, strategy):
    self.strategy = strategy

  def execute(self, num1, num2):
    return self.strategy(num1, num2)

class OperationAdd(object):
  def __call__(self, num1, num2):
    return num1 + num2


class OperationSub(object):
  def __call__(self, num1, num2):
    return num1 - num2


if __name__ == '__main__':
  con = Context(OperationAdd())
  print "10 + 5 =", con.execute(10, 5)

  con = Context(OperationSub())
  print "10 - 5 =", con.execute(10, 5)

您应该查看规则设计模式。它看起来与您给出的示例代码非常相似,由一个基本接口组成,该接口定义了一个确定是否满足某个规则的方法,然后根据不同的规则定义了不同的具体实现。据我所知,switch语句将变成某种简单的循环,它只对事物进行求值,直到满足或失败规则的组合

interface IRule {
    bool isSatisfied(SomeThing thing);
}

class RuleA: IRule {
    public bool isSatisfied(SomeThing thing) {
        ...
    }
}

class RuleB: IRule {
    ...
}

class RuleC: IRule {
    ...
}
组成规则:

class OrRule: IRule {
    private readonly IRule[] rules;

    public OrRule(params IRule[] rules) {
        this.rules = rules;
    }

    public isSatisfied(thing: Thing) {
        return this.rules.Any(r => r.isSatisfied(thing));
    }
}

class AndRule: IRule {
    private readonly IRule[] rules;

    public AndRule(params IRule[] rules) {
        this.rules = rules;
    }

    public isSatisfied(thing: Thing) {
        return this.rules.All(r => r.isSatisfied(thing));
    }
}

// Helpers for AndRule / OrRule

static IRule and(params IRule[] rules) {
    return new AndRule(rules);
}

static IRule or(params IRule[] rules) {
    return new OrRule(rules);
}
对某事物运行规则的某些服务方法:

class SomeService {
        public evaluate(IRule rule, Thing thing) {
            return rule.isSatisfied(thing);
        }
    }
用法:

// Compose a tree of rules
var rule = 
    and (
        new Rule1(),
        or (
            new Rule2(),
            new Rule3()
        )
    );

var thing = new Thing();

new SomeService().evaluate(rule, thing);

这里也回答了这个问题:

您能提供一些if-else语句的示例吗?国家模式的使用是否有相似之处?我认为“责任链”-模式可用于此处:感谢您提供的信息。您能否提供一些示例,这些模式有助于减少if/else。看起来是一个很好的示例,但可能不适合我的要求。我已编辑了我的问题,以包括连续逻辑的示例。我对规则1和其他一些类的某些属性具有条件逻辑规则二的属性(可能包括规则一中使用的一些属性)。为原始答案提供学分:):谢谢,但我的要求是不使用任何规则引擎,项目原因:(,因此我正在寻找一些设计模式。规则引擎是实现BRs的完美候选。以我个人的经验,它生成的代码超级干净且易于维护。并且将开发时间减少了几个数量级。它可能不适合我的要求。我已将我的问题编辑为包含sampl我对规则1的类的一些属性和规则2的一些其他属性(可能包括规则1中使用的一些属性)有条件逻辑。你也可以查看一篇博客文章,其中解释了规则设计模式是如何工作的