在我的工厂方法中,我使用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 举报,一经查实,本站将立刻删除。