【问题标题】:Design patterns regarding if...else statements关于 if...else 语句的设计模式
【发布时间】: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
     } 
     ...
  }
...
}

在策略模式的情况下,如果我理解正确,我需要为每个条件创建一个类。但不确定这是否是正确的方法,因为条件/类的数量会随着每个参数呈指数增长。有没有适当的方法来处理这种情况?

【问题讨论】:

标签: if-statement design-patterns


【解决方案1】:

假设有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!
}

这样,您也可以将可配置数据与通用逻辑分开。

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    相关资源
    最近更新 更多