首先,不清楚为什么要从泛型类派生出类,而不直接使用泛型类。同样不清楚为什么需要工厂而不是直接实例化所需的类。这些模式很重要且有用,通常是解决某些问题的唯一方法,但它们并不是必需品。您应该有充分的理由来实现它们。
尽管如此,我假设您确实有充分的理由,并且为了简洁起见省略了这些理由。
使用工厂模式的重点是让某些代码实例化正确的类,而不需要该代码知道正确的类。请注意,在您的示例中
缺少此分离:调用
MyClassFactory.CreateMyClass<T> ()
的人
必须知道正确的类,因为该代码必须将类型作为泛型参数传递,以确定正确的类。如果我足够了解调用
CreateMyClass<int> ()
,那么我足够了解调用
new MyDerivedIntClass ()
。
实现工厂模式的两种主要方法是静态函数和工厂类。
使用这两种方法,您都需要在泛型“下方”拥有一个抽象基类或接口:
public interface IMyInterface
{
string Foo ();
}
public abstract class MyGenericBaseClass<T> : IMyInterface
{
abstract string Foo ();
}
使用静态函数,需要在某处定义一个委托类型(省略类范围):
delegate IMyInterface MyInterfaceFactory ();
类可以实现它们以返回正确的类型。
public sealed class MyDerivedIntClass : MyGenericBaseClass<int>
{
static IMyInterface CreateObject () { return new MyDerivedIntClass (); }
}
public sealed class MyDerivedStringClass : MyGenericBaseClass<string>
{
static IMyInterface CreateObject () { return new MyDerivedStringClass (); }
}
你将静态函数传递给实例化对象的函数:
void Bar (MyInterfaceFactory factory)
{
IMyInterface mySomething = factory ();
string foo = mySomething.Foo ();
}
void FooBarAnInt ()
{
Bar (MyDerivedIntClass.CreateObject);
}
第二种方法是使用工厂类:
public interface IMyInterfaceFactory
{
IMyInterface CreateObject ();
}
public class MyDerivedIntFactory : IMyInterfaceFactory
{
public IMyInterface CreateObject () { return new MyDerivedIntClass (); }
}
public class MyDerivedStringFactory : IMyInterfaceFactory
{
public IMyInterface CreateObject () { return new MyDerivedStringClass (); }
}
void Bar (IMyInterfaceFactory factory)
{
IMyInterface mySomething = factory.CreateObject ();
string foo = mySomething.Foo ();
}
void FooBarAnInt ()
{
Bar (new MyDerivedIntFactory ());
}
请注意,您可以(并且可能应该)将工厂类也设置为单例模式,但这是一个不同的问题。此外,您可以使用抽象基类代替接口;您需要根据需要添加
abstract
(或
virtual
)和
override
。
从根本上说,某个人在某个地方以某种方式必须知道正确的对象类型来实例化。工厂对象的目的不是完全抽象化这些知识,而是将创建对象的代码与创建什么类型的对象的知识
分离开来。如果您不需要这种分离,则工厂模式并不特别有用。