I have a generic type which is shown below and want to create a factory to product an IItem by creating a descendant of TItem. Further would like to register the factory with the Parent TItem so that it can spawn multiple children objects of the type registered with the factory. I have seen this done with factories registered in a TDictionary but never with a parameterised type.
Type
IItem<T> = interface (IInterface)
Function GetParent:IItem<T>;
Procedure SetParent(aItem:IItem<T>);
property Parent:IItem<T> read GetParent write SetParent;
end;
TItem<T> = class(TInterfacedObject,IItem<T>)
private
FParent : IItem<T>;
FData : T;
Function GetParent:IItem<T>;
Procedure SetParent(aItem:IItem<T>);
public
property Parent:IItem<T> read GetParent write SetParent;
Constructor Create(aParent:IItem<T>);
end;
I would like to use a TItemFactory that creates an IITem implementing a descendant of TITem by passing in the class to a constructor. This factory will be called from within TItem so T will only be known when TITem is instantiated with a concrete data type. I have attempted to create this factory class but the compiler rejects my attempts to use the generic type. My question is how can I create the TItemFactory class and be able to pass in a class to be created.
My thoughts for this were:
TItemClass = class of TItem<T>;
TItemFactory<T>= class (TObject)
Function getItem:IItem<T>;
constructor Create(AClass:TItemClass);
end;
However this does not compile so I must be on the wrong track.
TFunc<IItem<T>>
– David Heffernan Nov 9 '15 at 6:49