【发布时间】:2013-05-31 04:15:47
【问题描述】:
我必须用数百行以下代码来实现某些业务规则
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>
【问题讨论】:
-
您能否提供一些 if else 语句的示例?如果有任何相似之处
-
使用状态模式?
-
我认为“责任链”模式可以在这里使用:oodesign.com/chain-of-responsibility-pattern.html
标签: java if-statement design-patterns specification-pattern