简体   繁体   English

具有泛型的C#工厂模式

[英]C# factory pattern with generics

I want to do a factory class for myInterface , however I can't call a constructor for a concrete class because the factory class is obliged to a specific parameter T . 我想为myInterface做一个工厂类,但是我不能为具体的类调用构造函数,因为工厂类必须使用特定的参数T

Is there a way to make a factory class for a generic interface? 有没有办法为通用接口创建工厂类?

Simplified Example 简化示例

interface myInterface<T>
{
    void work(T input);
    T getSomething();
}

class A : myInterface<int>
{
    //implementation
}

class B : myInterface<someClass>
{
   //implementation
}

interface Factory<R,T>
{
     R Create(T type);
}
class myFactory<T> : Factory<myInterface<T>, string>
{
     myInterface<T> Create(string type) {
          if(type == "A")
               //return new A object
          if(type == "B")
               //return new B object
          //some default behavior
     }
}

The Factory Pattern is generic by default, since the whole purpose of such pattern is to return objects of different types, depending on the value you provide to your method. 默认情况下,工厂模式是通用的,因为这种模式的整个目的是根据提供给方法的值返回不同类型的对象。

There shouldn't be much of a code within the factory other than whatever you need in order to initialize an object of the desired type. 除了初始化所需类型的对象所需的内容外,工厂内应该没有太多的代码。

In the code you've provided you're expecting to return an object of myInterface type, however it is not quite possible since you'll have to specify different return types which will be chosen by the value of your type parameter. 在您提供的代码中,您期望返回一个myInterface类型的对象,但是这是不可能的,因为您必须指定不同的返回类型,这将由type参数的值来选择。 You're losing the whole point of the Factory Pattern since you're already declaring a factory of a specific type - means you'll be creating objects only of that type (concept is lost). 您已经失去了工厂模式的全部要点,因为您已经声明了特定类型的工厂-这意味着您将仅创建该类型的对象(概念丢失)。

What I would have done is creating another class that will serve as a layer for both classes A and B (both classes will have to inherit from it). 我要做的是创建另一个类,该类将同时用作类A和B的层(这两个类都必须从中继承)。 Then I would declare the return type of your factory to the type of that class. 然后,我将工厂的返回类型声明为该类的类型。

Keep in mind that each class implements the same generic interface but of different type. 请记住,每个类都实现相同的通用接口,但类型不同。

Here's a brief example: 这是一个简单的示例:

    interface myInterface<T>
    {

    }
    class LayerClass
    {

    }
    class A : LayerClass, myInterface<int>
    {
        //implementation
    }

    class B : LayerClass, myInterface<object>
    {
       //implementation
    }

    public static void Main(string[] args)
    {

    }
    class myFactory<T>
    {
        LayerClass Create(string type) 
        {
            if(type == "A")
                return (LayerClass)new A();
            if(type == "B")
                return (LayerClass)new B();
            return null;
         }
    }

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

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