我可以在这种情况下使用工厂模式吗?

时间:2010-10-02 05:06:00

标签: .net design-patterns factory-pattern

我想知道我是否可以 - 以及如何 - 在这种情况下我可以使用工厂模式吗?

我有以下课程......

public interface IStub<T> where T : class
{
    IEnumerable<T> CreateStubs();
}

public FooStub : IStub<Foo>
{
    public IEnumerable<Foo> CreateStubs() { ... }
}


public BarStub : IStub<Bar>
{
    public IEnumerable<Bar> CreateStubs() { ... }
}

......等......

我想知道是否可以通过像...这样的工厂方法创建实例。

// This ends up returning an enumerable of Stubs.
var stubs = StubsFactory.CreateStubs<Foo>(); 

这是可能的/我是否在正确的轨道上,在这里?

3 个答案:

答案 0 :(得分:0)

喜欢这个。如果实现和存根不在同一个程序集或命名空间中,请修改Type.GetType行。

class UberCoolFactory
{
      public static T CreateStubs<T>()  
      {
          string ns = typeof(T).Namespace;
          string name = typeof(T).Name;
          string assembly = typeof(T).Assembly.GetName().Name;
          Type type = Type.GetType(string.Format("{0}.{1}Stub, {2}", ns, name, assembly));
          return (T)Activator.CreateInstance(type);
      }
 }

替代:

 class FactoryTwo
 {
    /// <summary>
    /// Search through all loaded assemblies that exists in the current directory.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static T CreateStub<T>() where T : class
    {
        string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string wantedTypeName = typeof(T).Name + "Stub";

        List<Type> foundTypes = new List<Type>();
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            if (!currentDir.Equals(Path.GetDirectoryName(assembly.Location)))
                continue;

            foreach (var type in assembly.GetTypes())
            {
                if (!type.Name.Equals(wantedTypeName))
                    continue;

                foundTypes.Add(type);
            }
        }


        if (!foundTypes.Any())
            return null;
        if (foundTypes.Count > 2)
            throw new AmbiguousMatchException("Found multiple stubs implementing '" + typeof(T).FullName + "'.");

        return (T) Activator.CreateInstance(foundTypes[0]);
    }
}

用法:

var instance = UberCoolFactory.CreateStubs<Foo>();
var instance2 = FactoryTwo.CreateStub<Foo>();

答案 1 :(得分:0)

扩展jgauffin关于搜索目标类型的答案:

string targetType = "BlahStub";
IEnumerable<Type> result = 
        from assembly in AppDomain.CurrentDomain.GetAssemblies()
        where !String.Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), assembly.Location, StringComparison.OrdinalIgnoreCase)
        from type in assembly.GetTypes()
        where String.Equals(type.Name, targetType, StringComparison.OrdinalIgnoreCase)
        select type;

答案 2 :(得分:0)

工厂声明:

static class StubsFactory<TStub, TClass>
            where TStub : IStub<TClass>
            where TClass : class
{
    public static IEnumerable<TClass> CreateStubs()
    {
        return ((TStub)Activator.CreateInstance<TStub>()).CreateStubs();
    }
}

用法:

IEnumerable<Foo> q = StubsFactory<FooStub, Foo>.CreateStubs();

这是你要找的吗?