views:

54

answers:

3

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' ?

A: 

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.

adrift
yeah, the code i don't want to access the Comment constructor is located in the same assembly. to create a different assembly should i create a new dll project ?
Attilah
yes, if you create a new dll project, any code in that project would not be able to create Comment instances as long as Comment's constructors are `internal`.
adrift
A: 

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.

BobbyShaftoe
A: 

What you're asking can be answered here. It's not exactly the same, but the solutions will be almost identicle.

I figure there are at least 3 tricks to solve your question, so it'll add more flexibility for you.

Neowizard