2017-04-19 134 views
0

我想为myInterface做一个工厂类,但是我无法调用具体类的构造函数,因为工厂类必须使用特定参数T带泛型的C#工厂模式

有没有办法为通用接口创建工厂类?

简单的例子

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 
    } 
} 
+0

那么,是什么或者不这段代码呢?你的研究表明了什么?您需要将要返回的实例转换为适当的类型。 – CodeCaster

回答

0

工厂模式是默认通用的,因为这种模式的整个目的是返回不同类型的对象,这取决于你提供给您的方法的价值。

除了需要初始化所需类型的对象之外,工厂内不应该有太多的代码。

在您提供你期待返回MyInterface的类型的对象的代码,但是这是不太可能的,因为你必须指定将通过价值来选择不同的返回类型的类型参数。由于您已经声明了特定类型的工厂,因此您将失去Factory Pattern的全部意义 - 意味着您将仅创建该类型的对象(概念丢失)。

我会做的是创建另一个类,它将充当A和B类的层(两个类都必须从中继承)。然后我会将工厂的返回类型声明为该类的类型。

请记住,每个类实现相同的通用接口,但具有不同的类型。

这里有一个简单的例子:

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