Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for class instantiation from only one single place?

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!

like image 951
Mats Avatar asked Dec 10 '22 14:12

Mats


1 Answers

It sounds like you are looking for the factory pattern:

The factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.

Basically your Provider class is the factory that controlls the creation of instances of the Data class.

One thing you could do control this would be to place these two types in their own assembly and make the constructor for Data be internal but the class itself public. This would mean that anyone who references the assembly would be forced to use the Provider class to create instances of Data (unless they used reflection, of course).

like image 135
Andrew Hare Avatar answered Jan 22 '23 22:01

Andrew Hare