【发布时间】:2011-07-22 08:23:56
【问题描述】:
我想控制一堆类的创建,这些类都共享一个公共接口,并且在构造中都需要一些逻辑。另外,除了类工厂之外,我不希望任何其他代码能够从这些类创建对象。
我的主要绊脚石是:
(1) 为了使通用方法能够创建类的实例,我需要 new() 约束,这意味着我必须在类上有一个公共构造函数,这意味着它们可以公开创建。
(2) 另一种方法是类本身具有一个返回类实例的静态方法。但是我不能从我的泛型类中调用它,因为我需要处理接口/类型,而你不能通过接口获得静态。
这是我目前拥有的那种东西,但它使用了 new() 约束,它允许我的类被公开创建:
internal static class MyClassFactory
{
internal static T Create<T>(string args) where T : IMyType, new()
{
IMyType newThing = new T();
newThing.Initialise(string args);
return (T)newThing;
}
}
public interface IMyType
{
void Initialise(string args);
}
public class ThingA: IMyType
{
public void Initialise(string args)
{
// do something with args
}
}
非常感谢任何帮助:)
【问题讨论】:
-
不要做通用工厂。创建一个抽象工厂(使用初始化代码和一个抽象的 DoCreate/CreateUnitialized/...),然后为每个类添加一个工厂。
标签: c# generics static factory