c# – 无法在不使用反射的情况下降低Factory方法中的圈复杂度

在我的工厂方法中,我使用Switch语句来创建具体对象.这导致非常高的圈复杂度.这是一个示例代码:
private static UnitDescriptor createUnitDescriptor(string code)
{
     switch (code)
     {
         case UnitCode.DEG_C:
             return new UnitDescriptorDegC();

         case UnitCode.DEG_F:
             return new UnitDescriptorDegF();

         :
         :
         default:
             throw new SystemException(string.format("unknown code: {o}",code);
      }
  }

我怎样才能重构这个以减少圈复杂度?如果我使用反射创建对象或其他东西来构建对象,它比上面的方法更好吗?

解决方法

您可以使用Dictionary完全删除switch语句:
class MyClass
{
    private static Dictionary<string,Func<UnitDescriptor>> dict = new Dictionary<string,Func<UnitDescriptor>>();

    static MyClass()
    {
        dict.Add(UnitCode.DEG_C,() => new UnitDescriptorDegC());
        dict.Add(UnitCode.DEG_F,() => new UnitDescriptorDegF());
        // Other mappings...
    }

    private static UnitDescriptor createUnitDescriptor(string code)
    {
        Func<UnitDescriptor> value;
        if (dict.TryGetValue(code,out value))
        {
            return value();
        }

        throw new SystemException(string.Format("unknown code: {0}",code));
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


c语言数组越界会怎么样
c语言指针怎么等于数组
c语言数组怎么存入文字
c语言中怎么显示数组
c语言数组元素怎么选
c语言数组怎么累加
c语言数组符号怎么输入
c语言怎么用长数组
c语言数组函数怎么输入
c语言数组怎么去掉差异
c语言怎么求解数组
c语言数组怎么用变量
c语言怎么申明数组
c语言怎么控制数组
c语言怎么计算数组长度
c语言数组怎么插星号
c语言数组怎么加长度
c语言中怎么输出数组
c语言怎么记住数组边界
c语言数组怎么输入符号