【发布时间】:2019-04-04 21:43:23
【问题描述】:
我是设计模式领域的新手,在处理包含多个条件的传统场景时遇到了麻烦。
假设我有一个服务(例如打印机),它具有多个属性并依赖于不同的参数(例如部门、文档类型)。当我想验证一个特定的参数组合是否正确设置了一个属性时,我最终会遇到很多 if...else 条件。
在伪代码中它看起来像这样:
class Printer
{
AttributeA a;
AttributeB b;
AttributeC c;
...
checkAttributeA(Department departement, Documenttype doctype);
checkAttributeB(Department departement, Documenttype doctype);
checkAttributeC(Department departement, Documenttype doctype);
...
};
Printer::checkAttributeA(Department departement, Documenttype doctype)
{
if (department == DepartmentA)
{
if (doctype == DocumenttypeA)
{
// do somthing
}
else if (doctype == DocumenttypeB) {
// do somthing else
}
...
}
else if (department == DepartmentB)
{
if (doctype == DocumenttypeA)
{
// do somthing
}
else if (doctype == DocumenttypeB) {
// do somthing else
}
...
}
...
}
在策略模式的情况下,如果我理解正确,我需要为每个条件创建一个类。但不确定这是否是正确的方法,因为条件/类的数量会随着每个参数呈指数增长。有没有适当的方法来处理这种情况?
【问题讨论】:
-
Chain of responsibility 设计模式可能是一个解决方案,我在 Alternative way of implementing nested if statement 线程上详细介绍了如何在 java 中使用
标签: if-statement design-patterns