"Tim" <Ti*@discussions.microsoft.com> a écrit dans le message de news:
A1**********************************@microsoft.com...
| Thanks for the sample Joanna and the links - Ignacio . From the sample,
| it appears that I have to add a switch statement for every new type of
object
| that I would like to create.
|
| But, according to the requirements of the project, I shouldn't have to
| make any code change in order to create a new type of object. The client
or
| anybody will just add the assembly and type details in the config file.
I
| wouldn't even know what kind of object would be created runtime.
|
| Is it still possible to use the factory pattern?
Yes, using reflection you certainly can create an extendable factory by
changing the factory method's signature like this :
public static class MyClassFactory
{
public static BaseType Create(Type classType)
{
if (! typeof(BaseType).IsAssignableFrom(classType))
throw new Exception("Can't create instance of this type");
return (BaseType) Activator.CreateInstance(classType);
}
}
As you can see, you would have to ensure that all the anticipated types
would have to have the same constructor signature (in this example a
default, noargs constructor).
As to a completely open Class Factory, I don't think that this is a good
idea as you would have to cater for possible differing constructor
parameters and, to cater for types that don't inherit from a fixed type
(apart from Object), you would have to resort to determining what parameters
were required by the constructor and you would have to return an Object, so
you might as well just use the Activator.
Are you really saying that you want a means of creating *any* type or just
those that derive from a particular base type ?
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer