开发者

factory class that prevents direct instantiation

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 Co开发者_高级运维mment 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' ?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜