我必须实现数百行以下代码的某些业务规则:
if this
then this
else if
then this
.
. // hundreds of lines of rules
else
that
我们是否有任何设计模式可以有效地实现这一点或重用代码,以便将其应用于所有不同的规则? 我听说过规约模式(Specification Pattern),它创建了类似以下内容:
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>