c# - 不使用反射无法降低工厂方法中的圈复杂度

标签 c# vb.net design-patterns reflection factory-method

在我的工厂方法中,我使用 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));
    }
}

关于c# - 不使用反射无法降低工厂方法中的圈复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18398377/

相关文章:

VB.NET:如何动态选择 ListView 项?

c# - 复杂服务层 IoC 的最佳实践

c# - ASP.NET C# : Which Design Pattern should I use and why?

c# - 当我将鼠标悬停在组合框项目上时引发事件

c# - 如何将 sql 表中的多列分配给 List<> 中的单列

C# 如何判断 IEnumerable 是否可变?

asp.net - 在 VB 代码中无法访问 WebForms ScriptManager 标记

c# - 是否可以在编译时获取程序集信息而无需反射?

c# - 如何遍历对象的成员变量?

mysql - 设计问题: symfony2 ,doctrine2,mysql数据库