Click to See Complete Forum and Search --> : Making a strong factory/prohibiting programmer use of NEW keyword


cjard
January 9th, 2006, 09:09 AM
Hi guys..

I have a simple structure:

ObjParent is the base class from which my children inherit. I want a factory class that manufactures appropriate children and i dont want the programmer making his own children..

Dim x as ObjParent = FactoryClass.Manufacture("some influencing string")


Manufacture returns one of a number of child types ObjChildA, ObjChildB etc. I dont want the programmer to be able to make a New ObjParent or any New ObjChildX (where X varies)


how do i do this? I tried making the factory and the Parent/Children in the same namespace and making the constructors protected, but it doesnt work this way?

jhammer
January 9th, 2006, 09:40 AM
Try this (I did not try this myself):
Set the constructor of the instansiated objects to be Friend.
Only classes in the same assembly will be able to instanciate those objects.

Alsvha
January 10th, 2006, 02:01 AM
Can't you just set the New() sub to private instead of public?

Private Sub New()

That way you can't call new from outside the class itself, but has to go through your factory methods.

jhammer
January 10th, 2006, 03:00 AM
If you set the constructor to be private, then the class itself must be the factory of itself (like in Singleton pattern - the Instance static property).
You will not be able to instanciate the object in another factory class.
That is why I suggested to use Friend modifier for the constructor - only classes from the same assembly can call the constructor.

jhammer
January 10th, 2006, 03:00 AM
If you set the constructor to be private, then the class must be the factory of itself (like in Singleton pattern - the Instance static property).
You will not be able to instanciate the object in another factory class.
That is why I suggested to use Friend modifier for the constructor - only classes from the same assembly can call the constructor.