TGizmo = class(TObject)
// stuff here
end;
TGizmoClass = class of TGizmo;
TGizmoFactory = class(TObject)
private
FHashedListOfGizmoClasses: TClassHashList;
public
procedure RegisterClass(const ClassKey: string; ClassType: TGizmoClass);
function CreateObject(const ClassKey: string): TGizmo;
end;
As you can see I pass in a key and a class type, then in CreateObject I
simply look up the key in the hash, call TGizmoClass.Create and *bam* there
is my new object.
My question is: How can I create a type-safe class type to pass into my
factory? All the examples I see require creating a concrete factory for
every concrete class but that seems like a waste. I'm sure I'm just
overlooking something super simple.
Thanks,
Shawn
Are you using .NET 2.0 ?
If so, use the Dictionary<K,V> instead of your HashList, but a factory
method can be really simple :
public static class GizmoFactory
{
public static Gizmo CreateObject<T>() where T : Gizmo, new()
{
return new T();
}
}
This is then used like this :
public class Gizmo
{
}
public class Derived : Gizmo
{
}
void Test()
{
Gizmo g = GizmoFactory.CreateObject<Derived>();
...
}
But then I guess you might as well use the straigtforward constructor call
anyway :-(
If you want to use a string key for a hash list that has a type value, then
this becomes a bit more difficult and you will have to lose type safety in
order to use Activator.CreateInstance() instead to create your instances.
I have created a C# metaclass but it is not typesafe at compile time, if you
use System.Type as the value part of a Dictionary key, then you can only
check for type at runtime.
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer
> My question is: How can I create a type-safe class type to pass into my
> factory? All the examples I see require creating a concrete factory for
> every concrete class but that seems like a waste. I'm sure I'm just
> overlooking something super simple.
Generally you use the System.Type object.
System.Type t = typeof(Gizmo);
or
System.Type t = GizmoInstance.GetType();
then
Gizmo g = (Gizmo)Activator.CreateInstance(t, constructor_params);
--
Marc Rohloff [TeamB]
marc rohloff -at- myrealbox -dot- com