0

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.

  • Very difficult to know what you are asking. For sure you can write this code. May or may not be useful. What is your question? – David Heffernan Nov 6 '15 at 22:30
  • @David I have edited the question to be more specific about what I am trying to do here, hope that makes sense – cheechaway Nov 8 '15 at 22:34
  • I still cannot understand this. I cannot see any factory. Your interface is not good because all instantiations have the same GUID. – David Heffernan Nov 8 '15 at 22:40
  • Ok, removed the GUID off the interface and put up what I had been thinking for the factory. – cheechaway Nov 9 '15 at 5:55
  • 1
    Instead of passing the item class to the factory, pass TFunc<IItem<T>> – David Heffernan Nov 9 '15 at 6:49

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.