防止直接实例化的工厂类
如何创建一个工厂类来防止类的直接实例化?
比如说,我有一个 Comment 类,它只能从 CommentFactory 类实例化。 我不希望 Comment 能够直接实例化。
我想我可以这样做:
public partial class Comment
{
private Comment(){}
public Comment CreateComment(User user,string str)
{
Comment cmt=new Comment();
user.AddComment(cmt);
cmt.User=user;
return cmt;
}
}
这段代码干净吗?
现在,我面临的问题是 Comment 是一个部分类,部分实现由 Linq to SQL 完成。 Linq to SQL 创建了此类的公共构造函数,那么我该如何规避这个问题呢?有什么‘窍门’吗?
How to create a factory class that prevents direct instantiation of a class ?
say, i have class Comment that should only be instantiated from a class CommentFactory.
I don't want Comment to be able to be instantiated directly.
I figured I could do this :
public partial class Comment
{
private Comment(){}
public Comment CreateComment(User user,string str)
{
Comment cmt=new Comment();
user.AddComment(cmt);
cmt.User=user;
return cmt;
}
}
is this code clean ?
now, the problem i'm facing is that the Comment is a partial class with partial implementation done by Linq to SQL. and Linq to SQL creates a public constructor of this class, so how can i circumvent this ? is there any 'trick' ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您所问的问题可以在此处得到解答。虽然不完全相同,但解决方案几乎相同。
我认为至少有 3 个技巧可以解决你的问题,所以它会为你增加更多的灵活性。
What you're asking can be answered here. It's not exactly the same, but the solutions will be almost identical.
I figure there are at least 3 tricks to solve your question, so it'll add more flexibility for you.
如果 Comment 和 CommentFactory 位于同一程序集中,则将 Comment 的所有构造函数设置为内部将阻止程序集外部的任何代码创建 Comment 的实例。
If Comment and CommentFactory are in the same assembly, making all constructors of Comment internal will prevent any code outside of the assembly from creating instances of Comment.
您可以将构造函数标记为CommentFactory 所在的程序集的
internal
,然后让使用者访问CommentFactory 类。我不知道如何“执行”它。You can mark the constructor
internal
to an assembly that CommentFactory resides in and then have consumers access the CommentFactory class. I'm not sure how else to "enforce" it.