繁体   English   中英

工厂根据通用类型C#创建对象

[英]Factory Creating Objects According to a Generic Type C#

根据传递给Factory类的泛型类型实例化对象的最有效方法是什么,例如:

public class LoggerFactory
{
    public static ILogger<T> Create<T>()
    {
        // Switch Statement?
        // Generic Dictionary?
        // EX.: if "T" is of type "string": return (ILogger<T>)new StringLogger();
    }
}

你会怎么做? 哪个分支语句 等等...

我认为最好保持简单,也许是这样的:

public static class LoggerFactory
{
    static readonly Dictionary<Type, Type> loggers = new Dictionary<Type, Type>();

    public static void AddLoggerProvider<T, TLogger>() where TLogger : ILogger<T>, new()
    {
        loggers.Add(typeof(T), typeof(TLogger));
    }

    public static ILogger<T> CreateLogger<T>()
    {
        //implement some error checking here
        Type tLogger = loggers[typeof(T)];

        ILogger<T> logger = (ILogger<T>) Activator.CreateInstance(tLogger);

        return logger;
    }
}

您只需为要支持的每种类型调用AddLoggerProvider ,可以在运行时对其进行扩展,以确保您明确地将接口的实现添加到库中,而不是添加一些对象,由于Activator缘故不是很快,但是创建一个无论如何,记录器都不会成为瓶颈。 希望看起来还好。

用法:

// initialize somewhere
LoggerFactory.AddLoggerProvider<String, StringLogger>();
LoggerFactory.AddLoggerProvider<Exception, ExceptionLogger>();
// etc..

ILogger<string> stringLogger = LoggerFactory.CreateLogger<string>();

注意:每个ILogger<T>需要Activator的无参数构造函数,但这也可以通过add方法中的new()泛型约束来确保。

我想我会这样:

public class LoggerFactory<T>
{
    private static Dictionary<Type, Func<ILogger<T>>> LoggerMap = 
        new Dictionary<Type, Func<ILogger<T>>>
    {
        { typeof(string), 
            () => new StringILogger() as ILogger<T> },
        { typeof(StringWriter), 
            () => new StringWriterILogger() as ILogger<T> }
    };

    public static ILogger<T> CreateLogger()
    {
        return LoggerMap[typeof(T)]();
    }
}

您付出了可读性的代价(所有这些尖括号,斜角),但是如您所见,它几乎不需要程序逻辑。

尽管我通常建议使用依赖项注入框架,但是您可以通过反射来实现某些功能,以在可用类型中搜索实现适当的ILogger接口的类型。

我建议您仔细考虑哪些程序集将包含这些记录器实现,以及您希望该解决方案具有多大的可扩展性和防弹性。 在可用的程序集和类型上执行运行时搜索并不便宜。 但是,这是允许这种类型的设计扩展的简便方法。 它还避免了前期配置的问题-但是,它只需要一个具体类型就可以实现ILogger <>接口的特定版本-否则,您必须解决一个模棱两可的情况。

您可能需要执行一些内部缓存,以避免在每次调用Create()时进行反射的开销。

这是一些您可以开始使用的示例代码。

using System;
using System.Linq;
using System.Reflection;

public interface ILogger<T> { /*... */}

public class IntLogger : ILogger<int> { }

public class StringLogger : ILogger<string> { }

public class DateTimeLogger : ILogger<DateTime> { }

public class LoggerFactory
{
    public static ILogger<T> Create<T>()
    {
        // look within the current assembly for matching implementation
        // this could be extended to search across all loaded assemblies
        // relatively easily - at the expense of performance
        // also, you probably want to cache these results...
        var loggerType = Assembly.GetExecutingAssembly()
                     .GetTypes()
                     // find implementations of ILogger<T> that match on T
                     .Where(t => typeof(ILogger<T>).IsAssignableFrom(t))
                     // throw an exception if more than one handler found,
                     // could be revised to be more friendly, or make a choice
                     // amongst multiple available options...
                     .Single(); 

        /* if you don't have LINQ, and need C# 2.0 compatibility, you can use this:
        Type loggerType;
        Type[] allTypes = Assembly.GetExecutingAssembly().GetTypes();
        foreach( var type in allTypes )
        {
            if( typeof(ILogger<T>).IsAssignableFrom(type) && loggerType == null )
                loggerType = type;
            else
                throw new ApplicationException( "Multiple types handle ILogger<" + typeof(T).Name + ">" );                   
        }

        */

        MethodInfo ctor = loggerType.GetConstructor( Type.EmptyTypes );
        if (ctor != null)
            return ctor.Invoke( null ) as ILogger<T>;

        // couldn't find an implementation
        throw new ArgumentException(
          "No mplementation of ILogger<{0}>" + typeof( T ) );
    }
}

// some very basic tests to validate the approach...
public static class TypeDispatch
{
    public static void Main( string[] args )
    {
        var intLogger      = LoggerFactory.Create<int>();
        var stringLogger   = LoggerFactory.Create<string>();
        var dateTimeLogger = LoggerFactory.Create<DateTime>();
        // no logger for this type; throws exception...
        var notFoundLogger = LoggerFactory.Create<double>(); 
    }
}

取决于要处理的类型。 如果它很小(小于10),我建议您使用switch语句,因为它将快速且清晰地读取。 如果您想要更多,则需要一个查找表(哈希图,字典等)或一些基于反射的系统。

switch语句vs字典-性能无关紧要,因为将switch编译成字典。 因此,实际上,这涉及到可读性和灵活性。 该开关更易于阅读,另一方面,字典可以在运行时扩展。

您可以考虑在此处使用诸如Unity的依赖项注入框架。 您可以使用因子将返回的通用类型对其进行配置,并在配置中进行映射。 这是一个例子

1)我总是对人们录入日志的复杂性感到惊讶。 在我看来,总是显得过分杀伤力。 如果log4net是开源的,那么我建议您先看看它,实际上,您也可以使用它...

2)就我个人而言,我尽量避免类型检查-它违反了泛型的观点。 只需使用.ToString()方法即可完成。

嗯...实际上,您可以尝试对此一点点了解,具体取决于给定的运行时系统所支持的内容。 实际上,我会尽量避免在代码中出现任何条件语句,尤其是在多态和动态绑定的代码中。 您在那里有一个泛型类,那么为什么不使用它呢?

例如,在Java中,您可以特别利用那里提供的静态方法来执行以下操作:

public class LoggerFactory<T>
{
    public static ILogger<T> CreateLogger(Class<? extends SomeUsefulClass> aClass);
    {
        // where getLogger() is a class method SomeUsefulClass and its subclasses
        // and has a return value of Logger<aClass>.
        return aClass.getLogger();

        // Or perhaps you meant something like the below, which is also valid.
        // it passes the generic type to the specific class' getLogger() method
        // for correct instantiation. However, be careful; you don't want to get
        // in the habit of using generics as variables. There's a reason they're
        // two different things.

        // return aClass.getLogger(T);
    }
}

您可以这样称呼它:

public static void main(String[] args)
{
    Logger = LoggerFactory.createLogger(subclassOfUsefulClass.class);
    // And off you go!
}

这避免了必须有任何条件,并且更加灵活:除了SomeUsefulClass的子类(或者可能实现logger接口的任何类)的任何类都可以返回正确类型的logger实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM