不久前,我在一个我正在工作的网站上删除了一条责任链。该链将调用一种方法为网站生成一个动态表单。每个被调用的对象要么返回它们的表单,要么“传递球”给下一个对象以检索表单。这个网站有关于300+类的这种逻辑,在性能方面没有什么大不了的,但是我发现看到它和调试它是很可怕的。
因此,我决定删除链式调用,并将其替换为反射,我知道必须用唯一的静态“名称”调用哪个对象(在链中使用相同的名称来检查对象是否必须加载类的表单或“传递球”),通过放弃列表中的所有对象,我将检查该名称以确保调用正确的类/方法。
我知道反射在性能上应该更慢,但是经过一些测试之后,我看不到任何实质性的差别,而且由于代码更干净,所以更容易理解和调试。
所以我的问题是:
这是一种正确的方法,还是在这种情况下使用更好的模式?
当我编码的时候,我觉得我更多地使用反射,而我不知道这是否总是更好的选择。
这在一个班:
foreach (TemplateHandler t in objectList)
{
if (t.GetType().GetProperty("serviceCode") != null)
{
if (t.GetType().GetProperty("serviceCode").GetValue(t).ToString() == serviceCodeToCallFromParam)
{
return t.GetTemplateParam(serviceCodeToCallFromParam/*, ...other params...*/);
}
}
}在300+类中是这样的:
public override List<Form> GetTemplateParam(string serviceCode)
{
if (serviceCode == ClassServiceCode)
{
// long form logic build.
//..
}
else
{
if (successor != null)
form = successor.GetTemplateParam(serviceCode);
}
return form;
}发布于 2017-06-06 09:56:54
如果我必须从这两种方法中选择一种,反射解决方案看起来会更好。传球300次似乎毫无意义。
但是,正如你所提到的,表演可能是问题所在。如果您已经知道要调用哪个类来完成工作,那么为什么不实现一些类似于Builder或Factory模式的方法来创建一个适当类的实例并完成这些工作呢?
switch-case结构甚至更简单。在switch-case中放置和创建代码,并使用结果对象来完成工作。
编辑1:
public T CreateTemplate<T>() where T : ITemplate
{
ITemplate template = null;
if(typeof(T) == typeof(Type1Template))
template = new Type1Template(....);
else if(typeof(T) == typeof(Type2Template))
template = new Type2Template(....);
else
throw new TemplateException("Template type is not configured.");
return (T)template;
}编辑2
看看下面这样的东西是否有帮助:
public T CreateTemplate<T>()
{
ITemplate template = (T)Activator.CreateInstance(typeof(T));
return template;
}https://stackoverflow.com/questions/44386745
复制相似问题