If statement 关于if…else语句的设计模式
我是设计模式领域的新手,在处理包含多个条件的传统场景时遇到困难 假设我有一个服务,例如打印机,它有多个属性,取决于不同的参数,例如部门、文档类型。当我想验证一个特定的参数组合是否正确设置了一个属性时,我会得到很多if…else条件 在伪代码中,它将如下所示:If statement 关于if…else语句的设计模式,if-statement,design-patterns,If Statement,Design Patterns,我是设计模式领域的新手,在处理包含多个条件的传统场景时遇到困难 假设我有一个服务,例如打印机,它有多个属性,取决于不同的参数,例如部门、文档类型。当我想验证一个特定的参数组合是否正确设置了一个属性时,我会得到很多if…else条件 在伪代码中,它将如下所示: class Printer { AttributeA a; AttributeB b; AttributeC c; ... checkAttributeA(Department departement, Documen
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
}
...
}
...
}
在strategie模式的情况下,如果我得到了正确的结果,我需要为每个条件创建一个类。但不确定这是否正确,因为条件/类的数量会随着每个参数呈指数增长。是否有适当的方法来处理此类情况?假设有M个部门和N种文档类型,并且对于这两个值的每个可能组合,必须采取不同的操作
这样的问题陈述有一种内在的复杂性,您不能不定义所有这些操作M x N是什么,如果打印机的每个属性导致对部门和文档类型的每个可能组合采取不同的操作,那么您也必须单独定义它们
考虑一个四维矩阵。第一个维度是属性,第二个维度是部门,第三个维度是文档类型,第四个维度是组合这三个值时要采取的相应操作
您至少必须定义这些操作:
var matrix = {
AttributeA: {
DepartmentX: {
DocumentP: SomeActionA,
DocumentQ: AnotherActionA
},
DepartmentY: {
DocumentP: SomeActionB,
DocumentQ: AnotherActionB
}
},
AttributeB: {
// similar structure
},
// and so on...
};
现在,您可以使用一个函数,该函数接收属性、部门和文档类型,并执行以下操作:
function takeAction(attribute, department, documentType) {
// maybe do a sanity check of your inputs
matrix[attribute][department][documentType](); // calling the action!
}
这样,您就可以将可配置数据从通用逻辑中分离出来。设计模式可能是一种解决方案,我已经详细介绍了如何在java中使用线程