In short I want to prevent objects being instantiated anywhere except in designated static methods in a object factory class.
Is this possible?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If your factory and your classes are in the same assembly you can mark the constructors internal. This will make it so that no classes outside the assembly can call the constructors (without reflection). Your factory, being in the same assembly, sees the constructors as public and, thus, can access them.
Alternatively, you can make the constructors private and use reflection inside your factory to instantiate the objects. You take a small hit using reflection but this doesn’t have the assembly restriction and also serves to keep other classes in the same assembly from using anything other than the factory.