Is StaticFactory in a code server a well-known template?

3 answers

Edit: Please note that this answer was asked before the question was completely redesigned. Because of this, he now refers to things that were present only in the question, as originally indicated. I apologize for all the "dangling pointers". :-)


Short answer:

, , IFoo<T>. , ( , ).

:

? , , ?

, factory :

var stringFoo = FooFactory.CreateFoo<string>();

(string ) , ( , ). , factory IFoo<string>.

, , :

var stringFoo = StringFoo.Create();

, , factory StringFoo, , :

public class StringFoo : IFoo<string>
{
    ...

    public static StringFoo Create()  // or alternatively, return an IFoo<string>
    {
        return new StringFoo();
    }
}

IFoo<T>, if switch FooFactory.CreateFoo<T>, ( ).

, , factory, , ; , , , .


P.S.: , IoC. , , (, ) ; (, Autofac):

var builder = new ContainerBuilder();
builder.RegisterType<StringFoo>().As<IFoo<string>>();

:

using (var container = builder.Build())
{
    var stringFoo = container.Resolve<IFoo<string>>();
    ...
}

Resolve - . , StringFoo. , !: -)

0

, ? , .

Edit

, . , , . ?

0

- ...

public static class FooFactory
{
    private static readonly Dictionary<Type, Type> FooTypesLookup;

    static FooFactory()
    {
        FooTypesLookup = (from type in typeof(FooFactory).Assembly.GetExportedTypes()
                          let fooInterface =
                            type.GetInterfaces().FirstOrDefault(
                                x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IFoo<>))
                          where fooInterface != null
                          let firstTypeArgument = fooInterface.GetGenericArguments().First()
                          select new { Type = type, TypeArgument = firstTypeArgument })
            .ToDictionary(x => x.TypeArgument, x => x.Type);
    }

    public static IFoo<T> CreateFoo<T>()
    {
        var genericArgumentType = typeof(T);
        Type closedFooType;
        return FooTypesLookup.TryGetValue(genericArgumentType, out closedFooType)
                ? (IFoo<T>) Activator.CreateInstance(closedFooType)
                : null;
    }
}

IoC (Windsor, ..) , IFoo, , Activator.CreateInstance.

0
source

All Articles