C# 如果不使用反射,则无法在工厂方法中降低圈复杂度

C# 如果不使用反射,则无法在工厂方法中降低圈复杂度,c#,vb.net,design-patterns,reflection,factory-method,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:

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

如何重构它以降低圈复杂度?如果我使用反射来创建对象或其他方法来构建对象,它是否比上述方法更好?

您可以使用
字典
完全删除
开关
语句:

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));
    }
}
class-MyClass
{
私有静态字典dict=新字典();
静态MyClass()
{
dict.Add(UnitCode.DEG_C,()=>newunitdescriptoredegc());
dict.Add(UnitCode.DEG_F,()=>新单元描述符rdegf());
//其他映射。。。
}
专用静态UnitDescriptor createUnitDescriptor(字符串代码)
{
Func值;
if(dict.TryGetValue(代码,输出值))
{
返回值();
}
抛出新的SystemException(string.Format(“未知代码:{0}”,代码));
}
}

在默认情况下,尝试返回一个值,而不是引发异常,然后再次尝试ANKS Adi。。。很好的回答,现在我不必使用反射:)这里的性能问题,因为您的工厂需要为您的字典中的每个元素创建一个新实例。最糟糕的是,您的措辞必须是静态的,这意味着您将创建的所有实例都将保留在内存中,直到代码结束。我目前正在为您的问题搜索相同的解决方案,但没有浪费时间和空间优化,我还没有找到。@niconoe创建的实例不是静态的-当您使用完它们后,它们将被释放。唯一会永远保存在内存中的东西是字典和它所保存的东西(键字符串和值创建函数)。@AdiLester你在c中可能是对的,因为我不是专家,但我正试图用PHP解决这个难题,我知道这个解决方案不能用,因为我解释了原因。也许c#那样更聪明。但是你不能否认你会浪费时间,因为你需要构建所有的实例,为它们运行所有的构造。取决于建造商的业务,它可能是沉重的。。。