我有一个 T
类和一个创建 T
类型对象的工厂 TFactory
。
我想确保只允许工厂创建新的 T
对象。
半心半意的解决方案是要求工厂作为 T
构造函数中的参数,唯一的目的是只有至少带来工厂对象的人才能创建 T
的:
class T
{
public T(TFactory Tf)
{
if (!(Tf is TFactory))
throw new InvalidOperationException("No factory provided");
}
}
但是只要手边有TFactory
,就可以构造T
。
另一种方法是通过堆栈跟踪检查构造函数调用是否真的来自 TFactory 内部,但这对我来说似乎有点过分了。
第三种方法是将 T
和 TFactory 放在它们自己的程序集中,并使 T
的构造函数成为 internal
。但是一个新的项目和装配就是为了这个目的吗?
有人有更好的主意吗? (虽然我的代码是C#,但这可能是一个更笼统的问题)
最佳答案
这与您的第三种方法非常相似:将工厂声明为 T
的内部类,并将 T
的构造函数设为 private
:
public class T {
public class Factory {
public T GetT() {
return new T(); // simple implementation just for an example here
}
}
private T() {}
}
由于Factory
位于T
内部,它可以访问私有(private)构造函数,但外部代码不能。如果您不想创建单独的程序集,可以考虑这种方法。
请注意,您仍然可以将工厂类和 T
放在两个不同的文件中,使用 partial
类:
public partial class T {
private T() {}
// other stuff about T here...
}
// in another file
public partial class T {
public class Factory {
public T GetT() {
return new T();
}
// other stuff about Factory here...
}
}
关于c# - 工厂模式 : Restrict object construction to factory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56722102/