加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:27:06 所属栏目:百科 来源:网络整理
导读:在我的工厂方法中,我使用Switch语句来创建具体对象.这导致非常高的圈复杂度.这是一个示例代码: private static UnitDescriptor createUnitDescriptor(string code){ switch (code) { case UnitCode.DEG_C: return new UnitDescriptorDegC(); case UnitCode.
在我的工厂方法中,我使用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));
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读