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

发布于 2024-09-26 10:54:07 字数 577 浏览 2 评论 0原文

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

我有以下类.....

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>(); 

这可能/我在正确的轨道上吗?

I was wondering if I could - and how - I could use the Factory Pattern in this scenario?

I have a the following classes...

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() { ... }
}

.. etc ...

and I was wondering if it's possible to create the instances through a factory method like ...

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

Is this possible / am I on the right track, here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北城孤痞 2024-10-03 10:54:07

像这样。如果实现和存根不在同一程序集或命名空间中,请修改 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>();

Like this. Modify the Type.GetType line if the implementation and stub isnt in the same assembly or namespace.

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);
      }
 }

Alternative:

 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]);
    }
}

Usage:

var instance = UberCoolFactory.CreateStubs<Foo>();
var instance2 = FactoryTwo.CreateStub<Foo>();
ゞ记忆︶ㄣ 2024-10-03 10:54:07

扩展 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;

Extending jgauffin's answer about searching a target type:

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;
枕头说它不想醒 2024-10-03 10:54:07

工厂声明:

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();

这是您要找的吗?

Factory declaration:

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

Usage:

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

Is it what you're looking for?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文