C# .Net 4.0
I’d like to know how I can have a class which can only be instantiated from one single place. An example:
I’ve got a Provider class. This class exposes a method called GetData. When GetData is called, the Provider will instanciate a Data class, populate and return it. The Data class cannot be instanciated by anybody different then the Provider, so the only way to access the data will be through the Provider. Once GetData is called and a caller has received the Data class instance, he should be able to access properties/methods of this class.
How can this be done? Is there a pattern for this sort of problem? A short sample would be highly appreciated. Thanks in advance!
It sounds like you are looking for the factory pattern:
Basically your
Providerclass is the factory that controlls the creation of instances of theDataclass.One thing you could do control this would be to place these two types in their own assembly and make the constructor for
Databeinternalbut the class itselfpublic. This would mean that anyone who references the assembly would be forced to use theProviderclass to create instances ofData(unless they used reflection, of course).